Link to home
Start Free TrialLog in
Avatar of sreejesh
sreejesh

asked on

Virtual functions

#include <iostream.h>

class Animal
{
      public:
      virtual char* speak(int) {return "Silence";}
};
class Cat:public Animal
{
      public:
      virtual char* speak(int) {return "Meow";}
};
class Dog:public Animal
{
      public:
      virtual char* speak(short) {return "Bow-wow";}
};

int main()
{
      Animal *p = new Dog;
      cout << p->speak( 0 ) << endl;
      return 0;
}

The speech of dogs is supposed to be 'Bow-wow' but instead the program prints 'silence'.Why did the dog not bark?
ASKER CERTIFIED SOLUTION
Avatar of alexo
alexo
Flag of Antarctica image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
In C, a function is known by its name.  In C++, a function is known by its "signature", which is the name and the types of the arguments.  Therefore f(int) and f(short) are two different functions.

Now, for your example:

        Animal *p = new Dog;

Although p points to Dog, its static type is Animal*.

        /* ... */    p->speak( 0 )    /* ... */

The compiler does not know what actual object p will point to at run-time.  So, it generates code to call the virtual function whose signature is known at compile-time, based on the information it knows about p.

        class Animal
        {
        public:
            virtual char* speak(int) {return "Silence";}
        };

Since p is a pointer to Animal, the compiler will (virtually) call the speak(int) function.

        class Dog:public Animal
        {
        public:
            virtual char* speak(short) {return "Bow-wow";}
        };

p points to a Dog object.  However, the Dog object does not define a speak(int) finction (the speak(short) function has a different signature and thus considered a different function).  Therefore, the inherited speak(int) function of the superclass (Animal) is called.

Avatar of nietod
nietod

By the way, A nice thing about the Borland C++ compiler  (there aren't many) is that it warns you when you do this.  Most compilers don't warn you since this is legal C++.  However, almost no one every really wants to do this on purpose, so Borland has enough sense to warn you.
this looks like one of those PC-lint bug of the month ads.
Avatar of sreejesh

ASKER

Alexo, You pointed out the correct answer. Congrats ! and Thank You. Same to nietod and danny_pav also.
>> this looks like one of those PC-lint bug of the month ads.
Bingo!  No wonder the "Bow-wow" looked familiar...