#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?