C++ examples for Class:Polymorphism
Difference between the calls to the base class and derived class who() functions.
#include <string> #include <iostream> using std::string; class Animal/*from ww w . j a va 2 s . co m*/ { private: string name; // Name of the animal int weight; // Weight of the animal public: Animal(string aName, int wt); // Constructor void who() const; // Display name and weight }; class Lion: public Animal { public: Lion(string aName, int wt) : Animal(aName, wt) {} void who() const; // Public member to access protected base function }; class Fish: public Animal { public: Fish(string aName, int wt) : Animal(aName, wt){} void who() const; // Public member to access protected base function }; using std::string; // Constructor Animal::Animal(string aName, int wt): name(aName), weight(wt) {} // Identify the animal void Animal::who() const { std::cout << "My name is " << name << " and I weigh " << weight << "lbs." << std::endl; } // Identify the Lion void Lion::who() const { std::cout << "I am a lion.\n"; Animal::who(); // Call base function } // Identify the Fish void Fish::who() const { std::cout << "\nI am an aardvark.\n"; Animal::who(); // Call base function } int main() { Lion myLion("Leo", 400); Fish myFish("Algernon", 50); std::cout << "Calling derived versions of who():\n"; myLion.who(); myFish.who(); std::cout << "\nCalling base versions of who():\n"; myLion.Animal::who(); myFish.Animal::who(); }