eladidan
eladidan

Reputation: 2644

const member function clarification needed

I'm a little confused as to why this code compiles and runs:

class A
{
private:
    int* b;
public:
    A() : b((int*)0xffffffff) {}
    int* get_b() const {return this->b;}
};

int main()
{
    A a;
    int *b = a.get_b();
    cout<<std::hex<<b<<endl;
    return 0;
}

Output of running this code is FFFFFFFFas well... unexpected by me. Shouldn't this->b return const int* since it is in a const member function? and therefore the return line should generate a compiler-cast error for trying to cast const int* to int*

Obviously there's a gap here in my knowledge of what const member functions signify. I'd appreciate if someone could help me bridge that gap.

Upvotes: 4

Views: 145

Answers (4)

Robb
Robb

Reputation: 2686

Putting const after the function declaration like you have tells the compiler "Hey, I promise not to modfy *this!". Your method is simply an accessor.

See C++ FAQ LITE 18.10

Upvotes: 0

Bo Persson
Bo Persson

Reputation: 92391

No, the member is an int* const (as seen from the const function), which is totally different.

The pointer is const, not the object pointed to.

Upvotes: 4

user2100815
user2100815

Reputation:

The function returns an integer pointer by value - you can't change the class member it is a copy of via this value, so there is no const violation.

Upvotes: 2

Xeo
Xeo

Reputation: 131907

The const part of a member function just says that the function is allowed to be called when the this pointer (aka the object on which it is called) is const. It got nothing to do with the return value.

class A{
public:
  void non_const_func(){}
  void const_func() const {}
};

int main(){
  A a;
  a.const_func(); // works
  a.non_const_func(); // works too

  const A c_a;
  c_a.const_func(); // works again
  c_a.non_const_func(); // EEEK! Error, object is const but function isn't!

}

Upvotes: 2

Related Questions