virtual class inheritance

hi Can anybody please explain how the answer is 223 of the below problem
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
#include <iostream>
using namespace std;
class B
{   public:
        int n;
};
class X :public virtual B
{
};
class Y :virtual public  B
{ 
};
class Z:public B
{
};
class A :X ,Y, Z
{   public:
    A(){
        X::n=1;
        Y::n=2;
        Z::n=3;
        cout<<X::n<<Y::n<<Z::n<<endl;
    }
};
int main()
{
    A a;
    return 0;
}
Why don’t you copy the example as it is?:
https://en.cppreference.com/w/cpp/language/derived_class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct B { int n; };
class X : public virtual B {};
class Y : virtual public B {};
class Z : public B {};
// every object of type AA has one X, one Y, one Z, and two B's:
// one that is the base of Z and one that is shared by X and Y
struct AA : X, Y, Z {
    AA() {
        X::n = 1; // modifies the virtual B subobject's member
        Y::n = 2; // modifies the same virtual B subobject's member
        Z::n = 3; // modifies the non-virtual B subobject's member
 
        std::cout << X::n << Y::n << Z::n << '\n'; // prints 223
    }
};

The answer is in the comments.

X::n and y::n are the same object. Z::n is different.

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
#include <iostream>

struct B { int n; };
class X : public virtual B {};
class Y : virtual public B {};
class Z : public B {};
// every object of type AA has one X, one Y, one Z, and two B's:
// one that is the base of Z and one that is shared by X and Y
struct AA : X, Y, Z {
    AA() {
        X::n = 1; // modifies the virtual B subobject's member
        Y::n = 2; // modifies the same virtual B subobject's member
        Z::n = 3; // modifies the non-virtual B subobject's member
 
        std::cout << X::n << Y::n << Z::n << '\n'; // prints 223
    }
};

int main()
{
  AA a;

  std::cout << "Address of  X::n = " << (void*)(&a.X::n) << '\n';
  std::cout << "Address of  Y::n = " << (void*)(&a.Y::n) << '\n';
  std::cout << "Address of  Z::n = " << (void*)(&a.Z::n) << '\n';
}
@Enoizat : hi ,I didn't know the question was taken from the link you provided, it was asked in an interview i recently appeared in ,so i tried on cpp compiler as it is..
thanks for the reply ...
Last edited on
@Repeater thanks for the reply..
Topic archived. No new replies allowed.