In C++, the operator ::
is used to access classes, functions and variables in a namespace or class.
If the language specification used .
instead of ::
in those cases too like when accessing instance variables/methods of an object then would that cause possible ambiguities that aren't present with ::
?
Given that C++ doesn't allow variable names that are also a type name, I can't think of a case where that could happen.
Clarification: I'm not asking why ::
was chosen over .
, just if it could have worked too?
Due to attempts to make C++ mostly compatible with the existing C code (which allows name collisions between object names and struct tags), C++ allows name collisions between class names and object names.
Which means that:
struct data {
static int member;
};
struct data2 {
int member;
};
void f(data2& data) {
data.member = data::member;
}
is legit code.
So the answer to the question in the title is Yes, it would, isn't it?
@EnricoMariaDeAngelis it's not that simple. Were C++ developed as a completely new language, like Java or C#, the ambiguity could probably be avoidable. But C++ was developed as "C with classes", and that's why it's not. "Yes, it will" is a correct answer, but to a different question.
Wait, isn't the assignment line just showing that putting
.
or::
between the same two "words" has different effect (data.member
refers to themember
of thedata
object of classdata2
, whereasdata::member
refers to themember
of the classdata
)?Yes, but it's not something that language designers should be proud of. It's just an artifact of compatibility decisions.
Ok, I understand that how C++ is today and has been so far (also) depends on what C was at the time C++ developed from it. But talking of C++ as it is, and leaving aside why it is as it is, there would an ambiguity if all
::
were changed to.
. In a way you answered yes already. I simply cannot breach into you first comment. Maybe my level makes that comment look smoky to me.