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

C++Language Design

C++ Problem Overview


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?

C++ Solutions


Solution 1 - 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.

Solution 2 - C++

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.

Solution 3 - C++

There is difference between a::b and a.b where :: implies that a used as namespace, which means that it is namespace or typename. Provided that C++ supports non-virtual plural inheritance and that a variable can have same name as a type, this strips chances of referencing wrong object. It's necessary for template metaprogramming.

Another example would be &B::foo vs &B.foo in context of class B.

Solution 4 - C++

Let extend @Deduplicator example:

#include <iostream>

struct A {
    int i;
};

struct B : public A {
    int i;
    A A;
};

int main() {
    B x {1, 2};
    std::cout << x.i << '\n';
    std::cout << x.B::i << '\n';  // The same as the line above.
    std::cout << x.A.i << '\n';
    std::cout << x.A::i << '\n';  // Not the same as the line above.
}

Live on Coliru Viewer

Not having a possibility to differentiate with help of ::, which member we want to access, it is impossible to access members declared in a parent class with identical names.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJimmy R.T.View Question on Stackoverflow
Solution 1 - C++Kit.View Answer on Stackoverflow
Solution 2 - C++DeduplicatorView Answer on Stackoverflow
Solution 3 - C++Swift - Friday PieView Answer on Stackoverflow
Solution 4 - C++273KView Answer on Stackoverflow