0

I have the following piece of C++ code:

#include <iostream>

using namespace std;

class X{
    public:
        int i;
};
class Y: public X{
    public:
        int i;
};


int main()
{
    X ob1;
    X ob2;
    Y ob3;
    ob1.i = 1;
    ob3.X::i=2;
    ob3.i=3;
    ob2=ob3;
    cout << ob2.i;
}

I expect it prints 3 (while it does 2) because ob2.i seems to me to be equivalent to ob3.i which was set to 3 but it seems that the compiler assumes this as the inherited i from the class X. Why?

reyad
  • 1,392
  • 2
  • 7
  • 12
Mohammad
  • 145
  • 8
  • 3
    The behavior is called slicing and this post could help: https://stackoverflow.com/questions/274626/what-is-object-slicing , Take `foo` as `X::i` and `bar` as `Y::i`. – Louis Go Aug 10 '20 at 01:59
  • Also in C++, data member could not be overridden in C++, only virtual funcitons. – Louis Go Aug 10 '20 at 02:04
  • Why do you "expect it prints 3"? `X.i` was never set to 3 anywhere. It was set to 2. `X::i` and `Y::i` have absolutely nothing to do with each other. Just because the shown code sets `Y::i` to 3 does not automatically set `X::i` (of the same object) to 3, too. C++ does not work this way. – Sam Varshavchik Aug 10 '20 at 02:04
  • @LouisGo Right! – Mohammad Aug 10 '20 at 02:12
  • @Mohammad With full qualifiers, the lines of interest here are `ob3.X::i = 2`, `ob2.X::i = ob3.X::i`, `cout << ob2.X::i`. – dxiv Aug 10 '20 at 02:15

0 Answers0