Class method and variable with same name, compile error in C++ not in Java?

Because C++ is not Java. You can take the address of a member:

&Test::isVal

So you can't have two members have the same name, except that you can overload member functions. Even if you could disambiguate that by some kind of cast, the next problem would already arise at other places.

In C++, a lot of people including me usually call data members specially, like putting a m before their name. This avoids the problem:

class Test {
public:
    bool IsVal() const { return mIsVal; }
private:
    bool mIsVal;
};

The quick answer is "because that's the way C++ works." C++ doesn't have a separate name space for member variables and member functions (ie, "methods") where Java (apparently, as I haven't tried this) does.

In any case, remember the old story about the guy who went to a doctor and said "Doc, it hurts when I do this." To which the doctor replied "well, don't do that!" This is a language peculiarity on its way to becoming a Dumb Programmer Trick.


Functions in c/c++ are just pointers to a location in memory where the code is located, isVal (as a boolean) and isVal (as a function) are therefore ambiguous.


C++ applies name mangling to function names and global variables. Local variables are not mangled. The problem arises because in C you can access the address of a variable or a function (thus in C++ as well) e.g. :

struct noob{
    bool noobvar;
    void noobvar(){};
};

One can say, why not apply name mangling to local variables as well and then have an internal local representation such as

bool __noobvar_avar;
void __noobvar_void_fun;

and suppose that they receive the addresses during execution 0x000A and 0x00C0 respectively.

However if we write somewhere in the code:

&noob::noobvar

What should the program do ?

  1. return the address of the variable noobvar , i.e. 0x000A
  2. return the addres of the noobvar function , i.e. 0x00C0

You can see that since in C , and therefore in C++ , you can issue an "address of", it is not legal to have variables and functions with the same name within the same scope of resolution.

Tags:

C++

Java