Solved

virtual functions

Posted on 2011-02-16
3
304 Views
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;
obj1=new(B);

Then no need to worry about virtual.


# include<iostream>
using namespace std;

class A
{
public:
      virtual void disp();
};

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

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

0
Comment
Question by:v_eman
3 Comments
 
LVL 86

Expert Comment

by:jkr
Comment Utility
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 {

public:

virtual ~Car() {}

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

class Bus : public IVehicle {

public:

virtual ~Bus() {}

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

int main () {

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

srand((unsigned)time(NULL));

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

  int nDice = rand() % 10;

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

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

  (*i)->Drive();
  (*i)->Release();
 
}

return 0;
}

Open in new window

0
 
LVL 12

Expert Comment

by:trinitrotoluene
Comment Utility
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.

http://www.cplusplus.com/doc/tutorial/inheritance/
http://www.cplusplus.com/doc/tutorial/polymorphism/

class Father{

public :

virtual Walk();
};

class Son : public Father {

public:
virtual Walk();
};

//below is your client app
main()
{

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

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

delete aFamily;
aFamily = 0;

}

Open in new window

0
 
LVL 32

Accepted Solution

by:
phoffric earned 500 total points
Comment Utility
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:
                          Animal
                         /        \
                       /            \
                     /                \
               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 ) {
      zooArray[i]->disp();
   }

   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
{ 
public:
   virtual void disp() = 0; // pure virtual
   virtual ~Animal() { cout << " RIP" << endl;}
   Animal(int a = 1) : age(a) {}
protected:
   int age;
};

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

class Boa : public Snakes {
public:
   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
{
public:
   Mammal(int a=3) : Animal(a) {}
   void disp() { cout << "Mammal " ; }
   virtual ~Mammal() {cout << " - a Mammal  "; }
};

class Lion : public Mammal
{
public:
   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
{
public:
   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
{
public:
   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

0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

743 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now