5

I have a question on constant objects. In the following program:

class const_check{
    int a;
    public:
    const_check(int i);
    void print() const;
    void print2();
};

const_check::const_check(int i):a(i) {}

void const_check::print() const {
int a=19;
    cout<<"The value in a is:"<<a;
}

void const_check::print2() {
    int a=10;
    cout<<"The value in a is:"<<a;
}

int main(){
    const_check b(5);
    const const_check c(6);
    b.print2();
    c.print();
}

void print() is a constant member function of the class const_check, so according to the definition of constants any attempt to change int a should result in an error, but the program works fine for me. I think I am having some confusion here, can anybody tell me why the compiler is not flagging it as an error?

4 Answers 4

22

By writing

int a = 19;

inside print(), you are declaring a new local variable a. This has nothing to do with the int a that you declared inside the class const_check. The member variable is said to be shadowed by the local variable. And it's perfectly okay to declare local variables in a const function and modify them; the constness only applies to the fields of the object.

Try writing

a = 19;

instead, and see an error appear.

2
  • Oh i missed that...Silly Thanks
    – Jony
    Apr 3, 2010 at 20:42
  • At least when using gcc, you may switch on a warning for this situation: -Wshadow will gcc make raising warnings when a symbol shadows another. IMO it's a good thing to switch on a lot of these warnings, so that you do not run into unintended behaviour, like this one. I bet clang and other compilers do have a comparable command line flag.
    – kaba
    Sep 2, 2023 at 22:39
4

You aren't changing the instance variable a you are creating a local variable a in each method.

1

You're not changing the member variable a in either print() or print2(). You're declaring a new local variable a which shadows the member variable a.

-3

Also, unless I am mistaken, you forgot to actually declare the member variable const to begin with.

2
  • 1
    That has nothing to do with it. When a member function is const, that means that the this pointer is a const pointer to const, so you can't modify it or anything it points to - that includes member variables of that object (and even if you don't explicitly use this, you're always using it when accessing member variables from within a member function). If a member variable is const, then you can't modify it at all - even in a non-const member function. But in a const member function, you can't modify any member variables regardless of whether it's const or not. Apr 5, 2010 at 12:09
  • You're right - I missed that he declared the method const instead.
    – Puppy
    Apr 5, 2010 at 22:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.