Inheritance question!!!!
Hi im new at c++, could anyone help me on this?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
#include <iostream>
using namespace std;
class A
{
public:
int q;
A(int q = 0){ this->q = q;}
};
class B: virtual public A
{
public:
int r;
B(int q = 0, int r = 0):A(q){this -> r = r;};
};
class C
{
public:
A sum;
C(A stuff){sum = stuff;}
};
class D: virtual public C
{
public:
B sum2;
D(B stuff2): C(A(stuff2.q)){sum2 = stuff2;}
};
int main()
{
A one(5);
B two(4,5);
C three(one);
D four (two);
cout << four.sum2.q << endl; // 4
cout << four.sum.q << endl; // 4
four.sum2.q = 6;
cout << four.sum2.q << endl; //6
cout << four.sum.q << endl; //4
four.sum.q = 7;
cout << four.sum2.q << endl; //6
cout << four.sum.q << endl; //7
}
| |
How do I write the code such that there is only 1 class A item in D?
What do you mean? You want D::sum2 to refer to the same object as C::sum? If that's the case, you could do
1 2
|
B &sum2;
D(/*...*/):sum2(this->sum)//...
| |
Needless to say, this is only possible because C::sum is an A and D::sum2 is a B. If the types were swapped, this would not work.
Last edited on
Topic archived. No new replies allowed.