0

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!

  • This question shows a fundamental lack of understanding about how inheritance works. I recommend taking a look at our [list of textbooks](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Paul Sanders Jun 07 '21 at 19:19

1 Answers1

1

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

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770