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?
For example, suppose that two classes named A and B both have a member named x , and a class named C inherits from both A and B . An attempt to access x from class C would be ambiguous. You can resolve ambiguity by qualifying a member with its class name using the scope resolution ( :: ) operator.
The ambiguity that arises when using multiple inheritance refers to a derived class having more than one parent class that defines property[s] and/or method[s] with the same name. For example, if 'C' inherits from both 'A' and 'B' and classes 'A' and 'B', both define a property named x and a function named getx().
Solution of ambiguity in multiple inheritance: The ambiguity can be resolved by using the scope resolution operator to specify the class in which the member function lies as given below: obj. a :: abc(); This statement invoke the function name abc() which are lies in base class a.
If the derived class object needs to access one of the similarly named member functions of the base classes then it results in ambiguity because the compiler gets confused about which base's class member function should be called. Example: C++
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.
An example where both are valid, but refer to different objects:
#include <iostream> struct A { int i; }; struct B { int i; A B; }; int main() { B x {0, 1}; std::cout << x.B.i << '\n'; std::cout << x.B::i << '\n'; }
See live on coliru.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With