Virtual Function





Virtual Function:

            A virtual function is a special type of member function. It is defined in the base class and may be redefined in any class derived from this base class. Its name in the base class and in the derived classes remains the same. Its definition in these classes may be different. The virtual function in derived class is executed through the pointer of the public base class.

            A virtual function is declared by writing the word virtual before function declaration in the base class. The functions with the same name are declared in the derived classes. The use of the word virtual before function declaration in derived classes is optional. Once a function is declared virtual in a base class, it becomes virtual in all derived classes; even when the keyword virtual is not written in its definition in the derived classes.

            The derived classes may have different versions of a virtual function. A virtual function may he redefined in the derived classes. A redefined function is said to override the base class function.

 

Pure Virtual Function:

            The virtual function that is only declared but base class are not defined is called the pure virtual functions. A virtual function is made pure by preceding the declaration by means of the keyword virtual and by post fixing with = 0.

            The pure virtual simply tells the compiler that the function is pure. The class that contains the pure virtual function exists only to act as a parent or base of the derived classes. This function is implements in the derived classes.

For example,

class bb
{
public:
virtual void ppp( ) = 0;

class d1: public bb
{
public:
void ppp( )
cout << “First Derived class” << endl;
}

};
class d2: public bb
{

public:
void ppp()
{
cout << “Second Derived class” << endl;
}

};

 

Other Topics



Comments are closed.

Translator

    Translate to:

Get Adobe Flash playerPlugin by wpburn.com wordpress themes