tags:

views:

916

answers:

3
class Test {

      bool isVal() const {
          return isVal;
      }

  private:

      bool isVal;
};

On Compiling this file it says

testClass.cpp:9: declaration of `bool Test::isVal'

testClass.cpp:3: conflicts with previous declaration `bool Test::isVal()'

Although the same would work for java

class Test {

  private boolean isVal;

  public boolean isVal() {
      return isVal;
  }

}

Not sure why C++ cannot handle this.

+10  A: 

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 be served at another place. In C++, we usually call member variables specially, like putting a m before their name:

class Test {
public:
    bool IsVal() const { return mIsVal; }
private:
    bool mIsVal;
};
Johannes Schaub - litb
... and, under the covers, the functions don't really have the same name anyway, since they're distinguished by class and argument signature.
Charlie Martin
In C++, we usually call member variables specially, like putting a m before their name???? We do? Is that in the language spec? This is a perfect answer right up until that sentence and the example following it.
jmucchiello
joe_mucchiello, go out and count all the popular name mangling, like "data_", "_data", "mData", "m_data", etc... . i think it justifies my use of "usually".
Johannes Schaub - litb
(IIRC) Microsoft did the m_ thing first. I'm currently maintaining code that does it, but I'm not a fan. I'm OK with trailing underscore for private data members but for some reason I don't like the m_ prefix.
Max Lybbert
litb- I don't think people name mangle because you can't have a method and a member variable with the same name. Thus it is not relevant to the question. Thus my point about the answer being a good technical answer until it tangents into a style issue.
jmucchiello
+2  A: 

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.

Kevin Loney
+2  A: 

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.

Charlie Martin