Default
Google

Classes: Virtual Functions

Applies To: C++Builder 1 or higher
Category: C++ Language

Virtual functions are member of a base class that can be overridden in a derived class. They're used when a pointer to an object points to a base class and to a derived class.
 
To declare a virtual function, simply use the virtual keyword. Virtual functions must be declared in the base class:
 
class Base {
public:
    virtual void Do();
};
 
void Base::Do() {
    cout <<< "Base ";< "Base ";
}
 
You can override the virtual Do function in the derived class:
 
class Derived : public Base {
public:
    virtual void Do();
};
 
void Derived::Do() {
    cout <<< "Derived ";< "Derived ";
}
 
Now in your main code you can call the two versions of the Do function:
 
#include <conio>
#include <iostream>
using namespace std;
 
// ...
 
int main()
{
    Base *pBase = new Base;
    Derived *pDerived = new Derived;
 
    pBase->Do();
    pDerived->Do();
 
    delete pBase, pDerived;
 
    getch();
    return 0;
}

C++Builder Developer's Network
Copyright © Yoto Yotov



Acquiring image from ProHosting Banner Exchange