#include <iostream>
struct base
{
virtual void print_type() const {
std::cout << "base\n";
}
};
struct derived : public base
{
void print_type() const {
std::cout << "derived\n";
}
};
int main()
{
base b; // b is an object of type base. It can never be anything else.
b.print_type();
derived d;
d.print_type();
b = d; // If we set b equal to an object of type derived, it is still an object of type base.
b.print_type();
base* ptr = &b; // ptr is a pointer to some class in the base hierarchy
ptr->print_type(); // if we point it a a base class object, we get base class behavior
ptr = &d; // if we point it a derived class object, we get derived class behavior
ptr->print_type();
}
I2luY2x1ZGUgPGlvc3RyZWFtPgoKc3RydWN0IGJhc2UKewogICAgdmlydHVhbCB2b2lkIHByaW50X3R5cGUoKSBjb25zdCB7CiAgICAgICAgc3RkOjpjb3V0IDw8ICJiYXNlXG4iOwogICAgfQp9OwoKc3RydWN0IGRlcml2ZWQgOiBwdWJsaWMgYmFzZQp7CiAgICB2b2lkIHByaW50X3R5cGUoKSBjb25zdCB7CiAgICAgICAgc3RkOjpjb3V0IDw8ICJkZXJpdmVkXG4iOwogICAgfQp9OwoKaW50IG1haW4oKQp7CiAgICBiYXNlIGI7IC8vIGIgaXMgYW4gb2JqZWN0IG9mIHR5cGUgYmFzZS4gIEl0IGNhbiBuZXZlciBiZSBhbnl0aGluZyBlbHNlLgogICAgYi5wcmludF90eXBlKCk7CgogICAgZGVyaXZlZCBkOwogICAgZC5wcmludF90eXBlKCk7CgogICAgYiA9IGQ7IC8vIElmIHdlIHNldCBiIGVxdWFsIHRvIGFuIG9iamVjdCBvZiB0eXBlIGRlcml2ZWQsIGl0IGlzIHN0aWxsIGFuIG9iamVjdCBvZiB0eXBlIGJhc2UuCiAgICBiLnByaW50X3R5cGUoKTsKCiAgICBiYXNlKiBwdHIgPSAmYjsgICAgIC8vIHB0ciBpcyBhIHBvaW50ZXIgdG8gc29tZSBjbGFzcyBpbiB0aGUgYmFzZSBoaWVyYXJjaHkKICAgIHB0ci0+cHJpbnRfdHlwZSgpOyAgLy8gaWYgd2UgcG9pbnQgaXQgYSBhIGJhc2UgY2xhc3Mgb2JqZWN0LCB3ZSBnZXQgYmFzZSBjbGFzcyBiZWhhdmlvcgoKICAgIHB0ciA9ICZkOyAgICAgICAgICAgLy8gaWYgd2UgcG9pbnQgaXQgYSBkZXJpdmVkIGNsYXNzIG9iamVjdCwgd2UgZ2V0IGRlcml2ZWQgY2xhc3MgYmVoYXZpb3IKICAgIHB0ci0+cHJpbnRfdHlwZSgpOwp9