0
#include<iostream>
using namespace std;

class A {
    public:
        A():m(1){};
        int m;
};

class B : public A {
    public:
        B (): A(),m(2),n(3){};
        void print(){cout<<'?';};
        int m,n;
};

int main (int, char *[]) {
    B b;
    A a1 = b;
    cout<<a1.m<<endl;       // This prints out 1 instead of 2.

    
return 0;
};

Brief code explanation: I declared and defined two class A and B, where B inherits from A. Class A and B both contains member variable m.

When I say A a1 = b;, I understand that member variable n of instance b won't get copied to a1, because of class slicing. My question is why member variable m is not copied as well?

(My thought is like: Both instance a1 and b contain member variable m, so when initializing a1 with b, the copy constructor of a1 will be called, and member variable within class A will get copied from b.) Is that correct?

More generally, during class slicing, what exactly is copied to the recipient?

o_yeah
  • 688
  • 7
  • 17
  • See the dupe, this is called object slicing. If you have a more specific question, edit it into the question. – cigien Oct 25 '20 at 23:52
  • 2
    It's not a good idea to hide base members by using the same name in derived classes. The `B b` object contains *two* distinct `int m;` members: `b.m` and `b.A::m`. Slicing only copies the latter over to `a1`. – dxiv Oct 25 '20 at 23:56
  • 1
    The confusion comes because you have _two_ member variables with the same name, `A::m` and `B::m`. In the `A a1 = b;` declaration, the `A` base class of `b` is copied, which copies over the `A::m` value (which was initialized to 1 in `A::A`). – 1201ProgramAlarm Oct 25 '20 at 23:57
  • What exactly happens is that the target base class part is copied via its copy constructor. – user207421 Oct 26 '20 at 01:22

0 Answers0