Search code examples
c++inheritancepolymorphism

Usage of base class type pointer to the derived type object


Suppose we have the following code:

class Base
{
public:
    virtual void print()
    {
        cout << "I'm base" << endl;
    }
};

class Derived : public Base
{
public:
    void print() override 
    {
        cout << "I'm derived" << endl;
    }
};

int main()
{
    Base* b = new Derived();
    b->print();
}

What I cannot understand is: what are the benefits of creating an object in this way and not simply:

Derived* d = new Derived();

Is it only used when we want to access fields and properties of the base class, but for virtual functions use the overriden ones from the derived class?


Solution

  • In your particular code, there is no real benefit in using the first method over the second. However, consider when you have two (or more) derived classes and want to use a common pointer to an instance of one of those classes, the actual type depending on some (run-time) condition. That's when such polymorphism shows its usefulness.

    Something like the following:

    int main()
    {
        Base* b;
        std::cout << "Enter 1 or 2: ";
        int choice;
        std::cin >> choice;
        switch (choice) {
            case 1:
                b = new Derived1();
                break;
            case 2:
                b = new Derived2();
                break;
            default:
                b = new Base();
                break;
        }
        b->print();
    
        // ... other stuff to do with your polymorphic instance ...
    
        delete b; // ... and don't forget to delete it when you're done!
        return 0;
    }
    

    I'll leave it as 'an exercise for the reader' to provide the definitions of the Derived1 and Derived2 classes.