Inheritance classes
-
I have the following code. Why does not my x is displayed. I do not understand, X is returned by the getX() function wich is called from the derived class SecondClass() through an object of type FirstClass(). Initialization of X was done using constructor function FirstClass(int x). I did not want to use the initialization function like setX ().
#include using namespace std;
class FirstClass
{
private:
int x;
public:
FirstClass()
{
cout << "\n Default constructor FirstClass()." << endl;
}
FirstClass(int x)
{
cout << "\n Constructor FirstClass()." << endl;
this->x = x;
cout << "\n X = " << x << endl;
}
int getX()
{
return x;
}
};class SecondClass:protected FirstClass
{
private:
int y;
public:
SecondClass(int x):FirstClass(x)
{
cout << "\n Constructor SecondClass()." << endl;
}
void printX(FirstClass& obj)
{
cout << "\n X = " << obj.getX() << endl;
}
};int main()
{
FirstClass box1;
SecondClass box2(100);
box2.printX(box1);
return 0;
} -
I have the following code. Why does not my x is displayed. I do not understand, X is returned by the getX() function wich is called from the derived class SecondClass() through an object of type FirstClass(). Initialization of X was done using constructor function FirstClass(int x). I did not want to use the initialization function like setX ().
#include using namespace std;
class FirstClass
{
private:
int x;
public:
FirstClass()
{
cout << "\n Default constructor FirstClass()." << endl;
}
FirstClass(int x)
{
cout << "\n Constructor FirstClass()." << endl;
this->x = x;
cout << "\n X = " << x << endl;
}
int getX()
{
return x;
}
};class SecondClass:protected FirstClass
{
private:
int y;
public:
SecondClass(int x):FirstClass(x)
{
cout << "\n Constructor SecondClass()." << endl;
}
void printX(FirstClass& obj)
{
cout << "\n X = " << obj.getX() << endl;
}
};int main()
{
FirstClass box1;
SecondClass box2(100);
box2.printX(box1);
return 0;
}