Search code examples
c++inheritancepolymorphisminstantiation

For which class is the instance created and what is the derived class doing in this code?


What is the derived class doing in this code like:

class Base
{
public:
       virtual std::string Name(){ return "Base Class"}

};
class Derived : public Base
{
 public:
        std::string Name() {return "Derived Class"}
}

int main()
{
   Base* object = new Derived();
   return 0;
}

I was following a tutorial but didn't understand What does Derived class in The instantiation of Base Class was doing in the above code.


Solution

  • The goal is to implement polymorphism, it's a OOP concept which allows you, among other things, to make derived class methods override the base class.

    Consider the following:

    class Base {
    public:
        //virtual keyword allows method to be overriden
        virtual std::string Name() { return "Base Class"; }
        //virtual destructor needed for polymorphism otherwise it can lead to undefined behavior
        virtual ~Base(){} 
    };
    
    class Derived : public Base {
    public:
        //optional keyword override signal the method has been overriden
        std::string Name() override { return "Derived Class"; }
    };
    
    class Derived2 : public Base {
    public:
        std::string Name() override { return "Derived Class 2"; }
    };
    
    int main() {
    
        Base *object = new Derived();
        Base *object2 = new Derived2();
        Base *object3 = new Base();
        //collection of objects of type Base* which can hold any class of the family
        Base *collection[] = {object, object2, object3};
    
        for (auto &obj : collection) {//test print
            std::cout << obj->Name() << std::endl;
        }
    }
    

    As the comments explain, I can have a collection of different objects of the same family and when you call Name() the method call will deppend on the object.

    Output:

    Derived Class
    Derived Class 2
    Base Class