c++(cplusplus)-virtual-functions

VIRTUAL FUNCTION:

class Base

{

public:

virtual void create()

{

cout<<“Base Class” ;

}

};

class Derived : public Base

{

public:

void display()

{

cout<<“Derived class”;

}

};

void main()

{

Base *p,*q;

p = new Base();

p ->display();

y= new Derived();

y ->display();

}

The output of the program is: Base Class

Derived Class

As we had declared the function to be virtual, so run-time linking occurs and the derived class function is being invoked the second time.Otherwise if the function had not been declared virtual then both time base class function would have been called because the function address is statically bound during compile time in this case.

Virtual Constructors and Destructors

A constructor cannot be virtual because its virtual table would not be available in the memory when the constructor is invoked.

Destructors are called in the reverse order of inheritance. A virtual destructor is one that is declared as virtual in the base class and is used to ensure that destructors are called in the correct order. If a base class pointer points to a derived class object and later we use delete operator to delete the object, then the destructor of derived class  is not called.

#include <iostream.h>
class base
{
public:
~base()
{

}
};

class derived : public base
{
public:
~derived()
{

}
};

void main()
{
base *ptr = new derived();
delete ptr;
}

In this case the pointer is of type base, the base class destructor would be called but the derived class destructor would not be called even once. Hence MEMORY LEAK occurs.To avoid this, the destructor is made virtual in the base class as in the example shown below:

#include <iostream.h>
class base
{
public:
virtual ~base()
{

}
};

class derived : public base
{
public:
~derived()
{

}

};

void main()
{

base *ptr = new derived();
delete ptr;
}

Comments on this entry are closed.

css.php