virtual functions

Posted on 2011-02-16
Last Modified: 2012-05-11
I am a beginner in c++. I understand that, virtual function can be used to resolve the conflict. Something like this,
in the given example, if virtual is not used, the parent class function is called.

but , why some one wants to declare a pointer of parent class type object and define it for a child class object.

A *obj1;        //A is the base class
obj1=new(B) // B inherits A

what is the use? any good example?..

I will go for
B *obj1;

Then no need to worry about virtual.

# include<iostream>
using namespace std;

class A
      virtual void disp();

void A::disp()
   cout<<"Class: A"<<endl;
class B : public A
     void disp();      

void B::disp()
   cout<<"Class: B"<<endl;
int main()
    A *obj1;
    obj1 = new(B);
    return 0;

Question by:v_eman
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 86

Expert Comment

ID: 34911363
The following example might help illustrate the advantages of such a concept:
#include <iostream>
#include <vector>
using namespace std;

#include <stdlib.h>
#include <time.h>

struct IVehicle {

virtual void Drive () = 0;
virtual void Release () = 0;

class Car : public IVehicle {


virtual ~Car() {}

virtual void Drive () { cout << "Driving a car" << endl;}
virtual void Release () {delete this;}

class Bus : public IVehicle {


virtual ~Bus() {}

virtual void Drive () { cout << "Driving a Bus" << endl;}
virtual void Release () {delete this;}

int main () {

vector<IVehicle*> vVehicles;
vector<IVehicle*>::iterator i;


for ( int n = 0; n < 10; ++n) {

  int nDice = rand() % 10;

  if ( nDice >= 5)
    vVehicles.push_back(new Car);
    vVehicles.push_back(new Bus);

for (i = vVehicles.begin(); i != vVehicles.end(); ++i) {


return 0;

Open in new window

LVL 12

Expert Comment

ID: 34912584
why some one wants to declare a pointer of parent class type object and define it for a child class object.

Look at it from a real world perspective

Lets say you initially design a "Father" class and then create an object of it. The Father has certain characteristics or properties. Now your client application may have been using only the Father class and referring to its behaviour by calling functions defined in the Father class.

A "Son" object is created later. There will be something in common between Father and Son to the extent that the Son can be considered as being similar to the Father or even a type of "Father".
Let's take the example of "Walk" being a characteristic which both Father and Son have. Now you have defined a function "Walk" in Father and have called it in your client application in several places.

Sometime in the future you decide that you want to replace the Father's walk with the Son's walk and so then all you need to do is use the same Father pointer in your client application but just initialize it with a "Son" object.

Now because "Walk" was a virtual function you automatically end up calling Son's Walk function wherever Father's Walk was called.

This is putting it in very layman terms.

If you want to read up about virtual functions you also need to understand inheritance.

class Father{

public :

virtual Walk();

class Son : public Father {

virtual Walk();

//below is your client app

Father* aFamily = new Father; //or new Son();

aFamily->Walk(); //calls Father->Walk() or Son->Walk()

delete aFamily;
aFamily = 0;


Open in new window

LVL 32

Accepted Solution

phoffric earned 500 total points
ID: 34912871
A common use of polymorphism is to have a container of base class pointers. By container, I mean, for example, a vector, or a set, or a map, or an array. A common simple example is the class structure of an Animal base class:
                         /        \
                       /            \
                     /                \
               Snake         Mammal
                  /              /     |    \
                 /              /      |      \
                /             /        |       \
            Boa      Tiger     Lion     Monkey

I'll use an array since you say you are a beginner:
Animal * zooArray[] = {new Lion(18), monkey0, pBoa1, lion2, new Tiger(15), new Tiger, pLion1};

Open in new window

You see that the array is filled with pointers to the derived class. Here is the test driver using polymorphism as we loop through the Animal pointer array:
int main()
   Monkey *monkey0 = new Monkey;
   Boa *pBoa1 = new Boa(12);
   Lion * pLion1 = new Lion;
   Lion * lion2 = new Lion(20);

   Animal * zooArray[] = {new Lion(18), monkey0, pBoa1, lion2, new Tiger(15), new Tiger, pLion1};
                         // array of pointers to the abstract base class

   int numberAnimals = sizeof(zooArray)/sizeof(zooArray[0]);
   cout << "Have " << numberAnimals << " in our zoo" << endl << endl;

   int i;
   for( i=0; i< numberAnimals; ++i ) {

   cout << "\nEvenually, all the animals died" << endl;
   for( i=0; i< numberAnimals; ++i ) {
      delete zooArray[i];
   return 0;

Open in new window

The output is:
Have 7 in our zoo

Acquired Lion: 18 years old
Acquired Monkey: 5 years old
Acquired Boa: 12 years old
Acquired Lion: 20 years old
Acquired Tiger: 15 years old
Acquired Tiger: 10 years old
Acquired Lion: 9 years old

Evenually, all the animals died
destroying Lion, age = 18 - a Mammal   RIP
destroying Monkey, age = 5 - a Mammal   RIP
destroying Boa, age = 12 - a snake RIP
destroying Lion, age = 20 - a Mammal   RIP
destroying Tiger, age = 15 - a Mammal   RIP
destroying Tiger, age = 10 - a Mammal   RIP
destroying Lion, age = 9 - a Mammal   RIP

Open in new window

Here are the classes (note that the base class has a pure virtual method, so it cannot be instantiated):

class Animal // abstract class
   virtual void disp() = 0; // pure virtual
   virtual ~Animal() { cout << " RIP" << endl;}
   Animal(int a = 1) : age(a) {}
   int age;

class Snakes : public Animal
   Snakes(int a = 4) : Animal(a) {}
   void disp() { cout << "Snakes " ; }
   virtual ~Snakes() {cout << " - a snake" ; }

class Boa : public Snakes {
   Boa(int a = 3) : Snakes(a) {}
   void disp() { cout << "Acquired Boa: "  << age << " years old " << endl;;}
   virtual ~Boa() {cout << "destroying Boa, age = " << age; }

class Mammal : public Animal
   Mammal(int a=3) : Animal(a) {}
   void disp() { cout << "Mammal " ; }
   virtual ~Mammal() {cout << " - a Mammal  "; }

class Lion : public Mammal
   Lion(int a = 9) : Mammal(a) {}
   void disp() { cout << "Acquired Lion: "  << age << " years old" << endl; }
   virtual ~Lion() {cout << "destroying Lion, age = " << age; }

class Tiger : public Mammal
   Tiger(int a = 10) : Mammal(a) {}
   void disp() { cout << "Acquired Tiger: "  << age << " years old" << endl; }
   virtual ~Tiger() {cout << "destroying Tiger, age = " << age; }

class Monkey : public Mammal
   Monkey(int a = 5) : Mammal(a) {}
   void disp() { cout << "Acquired Monkey: "  << age << " years old" << endl; }
   virtual ~Monkey() {cout << "destroying Monkey, age = " << age; }

Open in new window


Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
TCP/IP Socket - connection close results in data lost 14 153
Fast, free, private online code repository / editor 7 113
I could not build boost code, 10 107
visual C++ 1 11
Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question