c++functionoopoverridingvirtual

Overriding vs Virtual


What is the purpose of using the reserved word virtual in front of functions? If I want a child class to override a parent function, I just declare the same function such as void draw(){}.

class Parent { 
public:
    void say() {
        std::cout << "1";
    }
};

class Child : public Parent {
public:
    void say()
    {
        std::cout << "2";
    }
};

int main()
{
    Child* a = new Child();
    a->say();
    return 0;
}

The output is 2.

So again, why would the reserved word virtual be necessary in the header of say() ?


Solution

  • This is the classic question of how polymorphism works I think. The main idea is that you want to abstract the specific type for each object. In other words: You want to be able to call the Child instances without knowing it's a child!

    Here is an example: Assuming you have class "Child" and class "Child2" and "Child3" you want to be able to refer to them through their base class (Parent).

    Parent* parents[3];
    parents[0] = new Child();
    parents[1] = new Child2();
    parents[2] = new Child3();
    
    for (int i=0; i<3; ++i)
        parents[i]->say();
    

    As you can imagine, this is very powerful. It lets you extend the Parent as many times as you want and functions that take a Parent pointer will still work. For this to work as others mention you need to declare the method as virtual.