I'm having trouble understanding how slicing occurs? for example, in this piece of code:
class A {
public:
virtual h() {
cout << "type A" << endl;
}
};
class B : public A {
public:
virtual h() override {
cout << "type B" << endl;
}
};
void f(A a) {
a.h();
}
void g(A& a) {
a.h();
}
int main() {
A a1 = B(); // a1 is A and doesn't recognize any B properties
A *a = new B();
f(*a);
g(*a);
}
I noticed that:
variable a1 doens't know it's a B, but variable a does know. I refer this is happening because in variable a1 the assignment to B is by value, in contrst to variable a, where I create a pointer to B.
same thing happens when I pass variable a to different functions - when I pass by value, it thinks it's an A, but when i pass by reference, it thinks it's B.
I would be happy if anyone could give me more extensive and deeper explanation. Thank you in advance!