Kevin M Kevin M - 13 days ago 5
C++ Question

C++ Inheritance with a const member without using a getter

I am trying to design a class that provide a function which do something depending on one of its attribute. I also want to do the same process, but with another value, this is why I created a derived class and modified the attribute.

Firstly, I had created a static attribute because the value is not depending of each object but to the class itself. Or, I can't inherit a static attribute and modify each classes' one.

Then, I decided to put my attribute in const to be able to use inheritance. I made a simple program to show you my problem. Here I would like that foo display the value of the object which call the method and not the Parent's value. Also, I would not like to use a getter because I will use variable many times in my methods, this is for image processing.

#include <iostream>

// Compile it with
// g++ -o child_test child_test.cpp -std=c++11

class Parent{
public:
Parent() {}
virtual void foo(){
printf("%d\n", this->bar);
}
private:
const int bar = 0;
};

class Child : public Parent{
public:
Child() : Parent() {}
private:
const int bar = 10;
};

int main(){
Parent * p = new Parent();
p->foo(); // Output : 0

Child * c = new Child();
c->foo(); // Output : 0 ? How could it be 10

Parent * cp;
cp = new Child();
cp->foo(); // Output : 0 ? How could it be 10
}

Answer

That's not how the language works. The function might be virtual, but the member variables (constants) are not.

If you want a different value in the base class, pass that to the constructor.

class Parent{   
    public:
        Parent(int value = 0) : bar(value) {}    
        virtual void foo(){
            printf("%d\n", this->bar);
        }    
    private:    
        const int bar = 0;    
};    

class Child : public Parent{    
    public:   
        Child() : Parent(10) {}
};
Comments