C++ Learning Resource Network!

 
 
 C++ Tutorials  >  Binding  >  Virtual Functions
 

Virtual Functions

While pointers are necessary for late binding, they are not sufficient to implement it.

Consider the following statements:

PC *Ptr;
Ptr = new PC_XT;
Ptr->get_ram_space();


The compiler always invokes the member function of the PC class although Ptr is pointing to an object of the PC_XT class. This happens because, binding takes place at the time of compilation, when the content of the pointer is not known. Thus, base class pointers alone are not sufficient to implement late binding.

To ensure late binding, the concept of virtual function needs to be understood. A virtual function is a function that is declared as virtual in a base class and is redefined by a derived class. A function is declared virtual because its execution depends on the contents of the base class pointer used to invoke it, which is not known at the time of compilation. To declare a function as virtual, its declaration is preceded by the keyword virtual.

Late binding is ensured in the PC class by declaring the function of the base class as virtual.

The following code segment contains the modified declaration of the get_ram_space() function making the function virtual.

Class PC
{


virtual int get_ram_space();


};
class PC_XT : public PC
{


int get_ram_space();


};

class PC_AT : public PC_XT
{


int get_ram_space();


};


The get_ram_space() member function of the PC class is a virtual function. When a virtual function is inherited, its virtual nature is also inherited. In the above code segment, the function get_ram_space() in PC_XT and PC_AT classes is virtual.

Pure Virtual Functions

A pure virtual function is a virtual function without any executable statements. Often the virtual functions of the base class are not used. For example, assume that the PC class you have seen earlier, is derived from a microcomputer class. If the microcomputer class also has a get_ram_space() function, it will never be invoked. This is because the microcomputer class is too generalized to have a definite RAM size. Only the functions in the derived class will be invoked. In such situations, the body of the virtual function can be removed.

A pure virtual function can be declared by equating the function declaration to zero. For example, the statement
Virtual int get_ram_space() = 0;
declares the function get_ram_space() to be a pure virtual function.
 

 
 

| Bookmark This Site |   | Links |   | Search |   | Submit |   | Contact |

  Copyright 2008 - 3008  CppTutor.com All rights reserved.