Cpp inheritance - Parent function, child variable

I have a class with a function and a subclass.
In the following code, I want to override the int x in a way that d.getX() return 40.

using std::cout, std::endl;

class Base {
protected:
    int x;
    int y;
public:
    Base(int y) : y(y) {};
    int getX() {
        return x;
    }
};

class Derived : public Base {
protected:
    int x = 40;
public:
    using Base::Base;
};

int main() {
    Base d(10);
    cout << d.getX() << endl; // want to print 40
    return 0;
}

Is this possible? Thank you!

Upvotes: 0

Views: 192

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597111

Well, for starters, you are not creating a Derived object, so your code to set the value of x to 40 is never called. It might even get optimized out completely.

But even so, Derived is declaring its own x member that shadows the x member in Base, so Base::x is never being assigned a value. You need to get rid of Derived::x and make Derived update Base::x instead.

Try this:

#include <iostream>
using std::cout;
using std::endl;

class Base {
protected:
    int x;
    int y;
public:
    Base(int y) : y(y) {};
    int getX() {
        return x;
    }
};

class Derived : public Base {
public:
    Derived(int y) : Base(y) { x = 40; }  
};

int main() {
    Derived d(10);
    cout << d.getX() << endl;
    return 0;
}

Online Demo

Upvotes: 1

Related Questions