Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 353
  • Last Modified:

virtual functions

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
v_eman
Asked:
v_eman
1 Solution
 
jkrCommented:
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
 
trinitrotolueneDirector - Software EngineeringCommented:
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
 
phoffricCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now