0
#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.

4
  • 2
    Use a separate member variable for the Derived class? Commented Apr 23, 2017 at 9:26
  • 5
    A variable only has one value at a time. Commented Apr 23, 2017 at 9:26
  • 3
    "I want to print 2 and 4 both" - std::cout << 2 << 4 << '\n'? Seriously, what do you mean? Commented Apr 23, 2017 at 9:31
  • @ChristianHackl I think it should be the accepted solution. Commented Apr 23, 2017 at 9:39

2 Answers 2

2

You need two variables to hold two values.

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.