virtual function specifier

From Cppreference

Jump to: navigation, search

Specifies that a function is virtual

Contents

[edit] Syntax

virtual function_declaration ;

[edit] Explanation

Virtual functions are functions whose behavior can be overridden in a inheriting class. As opposed to non-virtual functions, the overridden behavior is preserved even if there is no compile-time information about the actual type of the class.

virtual and static function specifiers are incompatible. static specifies that a function does not need an instance of a class, where virtual needs an instance of a class by its definition.

[edit] Example

class Parent {
public:
    void functionA();
    virtual void functionB();   //Note the keyword virtual
    void functionC();
};
 
class Child : public Parent {
public:
    void functionA();
    virtual void functionB();   //Note the keyword virtual
};
 
int main()
{
    Parent* p1 = new Parent;
    Parent* p2 = new Child;
    Child* c = new Child;
 
    p1->functionA();   //Calls Parent::functionA
    p1->functionB();   //Calls Parent::functionB
    p1->functionC();   //Calls Parent::functionC
 
    p2->functionA();   //Calls Parent::functionA because p2 points to a Parent
    p2->functionB();   //Calls Child::functionB even though p2 points 
                       // to a Parent because functionB is virtual
    p2->functionC();   //Calls Parent::functionC
 
    c->functionA();   //Calls Child::functionA
    c->functionB();   //Calls Child::functionB
    c->functionB();   //Calls Parent::functionC
 
    return 0;
}

[edit] See also