C++: Virtual Functions

---- Scenario 1 ----

class Parent {
    public:
        int foo();           // <-- called if Parent.foo is not virtual
};
class Child : public Parent {
    public:
        int foo();           // <-- called if Parent.foo is virtual
};

Child kid;
(Parent) kid.foo();        // calls PARENT version, because Parent.foo is not virtual

---- Scenario 2 ----

class Parent {
    public:
        virtual int foo();
};
class Child : public Parent {
    public:
        int foo();
};

Child kid;
(Parent) kid.foo();        // calls CHILD version, because Parent.foo is virtual

No comments: