Search code examples
c++inheritanceencapsulation

Derived class calls an inherited function that uses non-inherited members


I have a base class that has two private variables, and a public method to print them. By inheriting from it, I get a method that uses variables that aren't inherited to the derived class. However, it works and calls that method with the values given by base class constructor.

Even by adding to derived his own default constructor, and the same int x, y; variables, with different default values, the method prints the base class default ones. Why does this happen, and how can I avoid it? I'm aware of protected members but still what's happening here? I first tried this with derived class empty (without constructor and variables) and the result is the same. How can it use variables that are not inherited?

class base {
private:
    int x, y;

public:
    base(int px=1, int py=2)
        :x(px), y(py)
    {}

    inline void print() const {
        cout << x << ", " << y << '\n';
    }
};

class derived : public base {
private:
    int x, y;
public:
    derived(int px = 3, int py = 3)
        :x(px), y(py)
    {}
};

int main{
        derived e;
        e.print(); // prints 1, 2
}

Solution

  • base::print cannot see member variables in derived. You have a few options:

    1. Use protected if you actually want base::x and derived::x to be different.
    2. Pass px and py to base's constructor: derived(int px = 3, int py = 3) : base(px, py) { }
    3. Make base::print a virtual member function and override it in derived.

    Which option is best depends on your requirements.