Blair Davidson
Blair Davidson

Reputation: 951

const correctness and member pointers

I have const on the Accelerate method, yet I can call the power method. Is their a way to actually stop this.

class Engine{
public:
    void Power(){
    }
};

class Car{
public:
    Car() : p(new Engine()){}

    void Accelerator() const{
        p->Power();
    } 
    private:
        Engine* p;
};

Upvotes: 2

Views: 94

Answers (3)

aichao
aichao

Reputation: 7455

You can modify the member Engine as const*, which will make the Engine object pointed to by p in Car const:

class Engine{
 public:
  void Power(){
  }
};

class Car{
 public:
  Car() : p(new Engine()){}

  void Accelerator() const{
      p->Power();
  } 
 private:
  Engine const* p;
};

This will no longer compile:

test_const.cpp:12:9: error: member function 'Power' not viable: 'this' argument
      has type 'const Engine', but function is not marked const
        p->Power();
        ^
test_const.cpp:3:10: note: 'Power' declared here
    void Power(){
         ^

But this implies that no member of Car can modify *p, which is probably not what you intend. See @NathanOliver's comment for better answer.

Hope this helps.

Upvotes: 2

David Haim
David Haim

Reputation: 26536

For Car, a const method is a methods which does not modify Car member variables.

so, as long that Car::Accelerator does not make p point to a different location, it is valid.

since p is not modified in Accelerator (meaning it does not point to a different memory address), the program is valid.

the moment you make p point to a different location, the program fails to compile:

  void Accelerator() const {
        p= nullptr; //wrong
  } 

Upvotes: 2

Notinlist
Notinlist

Reputation: 16650

Const protection affects only the direct members, in this case the pointer only. Values outside this object (aka. pointed values) are not protected.

You have to decide if you consider the pointed value as yourself or someone else.

Upvotes: 2

Related Questions