Alex Rivera | Logout

Overriding vs Virtual

Asked 2010-05-28T22:29:08.157
50

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() ?

Edit
Report

1 Answer

-1

This is a very important aspect of c++ programming-- almost every interview I've been to, I get asked this question.

What happens if you change your main to:

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

Also, it's worth understanding what a vtable is.

answered 2010-05-28T22:37:29.337

Your Answer