waheed abbax
waheed abbax

Reputation: 13

How to access variable's value from base class in derived class?

#include<iostream>

class Foo {
    protected: // Make x visible to derived classes
        int x;
    public: 
        Foo() {
           x = 2;
        }
};

class Derived : public Foo {
    public: 
        Derived() {
            x = 4;
        }

        void print(){
            std::cout << x << std::endl;
        }
};


int main() {
    Derived a;
    a.print();
}

This prints 4.I want to access both the values of x in print.I want to print 2 and 4 both.Do I need to creat object of Foo in Derived class and access it through object.x?But that calls the constructor of Foo more than once.I don't want that to happen.

Upvotes: 0

Views: 1254

Answers (2)

Jesper Juhl
Jesper Juhl

Reputation: 31447

There is only one x in the object total. Not one in the Foo part and one in the Derived part. So when your Derived constructor assigns 4 to x then that is the value of the variable, period. If you need to hold two distinct values then you need two variables.

Upvotes: 0

Sergei
Sergei

Reputation: 550

You need two variables to hold two values.

Upvotes: 2

Related Questions