Virtual function magic only operates on pointers and references. - C++ Class

C++ examples for Class:Inheritance

Introduction

Passing an object by value will not enable the virtual member functions to be invoked.

Demo Code

#include <iostream> 
   //from ww  w . ja  va  2  s . c  om
class Pet 
{ 
public: 
   Pet():age(1) {  } 
    ~Pet() { } 
    virtual void speak() const { std::cout << "Pet speak!\n"; } 
protected: 
    int age; 
}; 
   
class Dog : public Pet 
{ 
public: 
    void speak() const { std::cout << "Woof!\n"; } 
}; 
   
class Cat : public Pet 
{ 
public: 
    void speak()const { std::cout << "Meow!\n"; } 
}; 
   
void valueFunction(Pet); 
void ptrFunction(Pet*); 
void refFunction(Pet&); 
   
int main() 
{ 
    Pet* ptr=0; 
    int choice; 
    while (1) 
    { 
         bool fQuit = false; 
          std::cout << "(1) dog (2) cat (0) quit: "; 
          std::cin >> choice; 
          switch (choice) 
          { 
          case 0:  
              fQuit = true; 
              break; 
          case 1:  
              ptr = new Dog; 
              break; 
          case 2:  
              ptr = new Cat; 
              break; 
         default:  
              ptr = new Pet; 
              break; 
          } 
           if (fQuit) 
           { 
            break; 
           } 
          ptrFunction(ptr); 
          refFunction(*ptr); 
          valueFunction(*ptr);  
    } 
    return 0; 
} 
   
void valueFunction(Pet mammalValue)  // This function is called last 
{ 
    mammalValue.speak(); 
} 
   
void ptrFunction (Pet *pPet) 
{ 
    pPet->speak(); 
} 
   
void refFunction (Pet &rPet) 
{ 
    rPet.speak(); 
}

Result


Related Tutorials