Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Would replacing ' :: ' with ' . ' create ambiguities in C++?

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?

like image 650
Jimmy R.T. Avatar asked Jan 31 '20 11:01

Jimmy R.T.


People also ask

What is ambiguous in C?

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.

Does multiple inheritance lead to ambiguity?

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().

How can we resolve ambiguity in multiple inheritance?

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.

What is ambiguity explain with an example in C++?

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++


2 Answers

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.

like image 193
Kit. Avatar answered Oct 15 '22 15:10

Kit.


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.

like image 43
Deduplicator Avatar answered Oct 15 '22 15:10

Deduplicator