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!

1
  • This question shows a fundamental lack of understanding about how inheritance works. I recommend taking a look at our list of textbooks. Commented Jun 7, 2021 at 19:19

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.