cpp/language/virtual

From Cppreference

Jump to: navigation, search

[edit] Usage

Virtual function declarations/definitions


[edit] Syntax

virtual <type> <function>([<type><variable>[, <type><variable>...]]);
  1. <type> is/are the type(s) of the variables.
  2. <function> is the name of the function.
  3. <variable> is/are the name(s) of the variable(s) used.
  4. Bold text must be typed as is
  5. Angle brackets denote a placeholder for a required value.
  6. Square brackets denote a placeholder for an optional value.
  7. Angle brackets nested inside square brackets indicate that it is required if anything inside the square brackets is used.
  8. Elipses (...) denote things that may be repeated.


[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;
}