#include <iostream>
#include <string>
class A
{
public:
A(int a) : _a(a) {}
virtual ~A() {}
virtual void f() const {std::cout << _a << std::endl;}
private:
int _a;
};
class B : public A
{
public:
B(int a, int b) : A(a), _b(b) {}
virtual void f() const {std::cout << _b << std::endl;}
private:
int _b;
};
int main()
{
B b (1,2);
A a (5);
A& ref = a;
ref = b;
ref.f();
return 0;
}
Conclusion:
1
I understand that when copying the received (extended) class object to an object of a base class, the derived object is cut and only the data of the base class is copied. But I thought that the virtual table 'ref' should now be like a virtual table 'b', therefore 'ref.f ();' should call the function:
void B::f() const {std::cout << _b << std::endl;}
But after copying the vtbl 'ref', the vtbl of class A remains. Why? Thank.
source
share