C++ examples for Class:Inheritance
Who() function from base class has the protected access specifier, the derived classes can public access the who() function.
#include <string> #include <iostream> using std::string; class Animal//from w w w .jav a2s . co m { private: string name; // Name of the animal int weight; // Weight of the animal protected: void who() const; // Display name and weight public: Animal(string aName, int wt); // Constructor }; 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 << "\nI am a lion.\n"; Animal::who(); // Call protected base function } // Identify the Fish void Fish::who() const { std::cout << "\nI am a fish.\n"; Animal::who(); // Call protected base function } int main() { Lion myLion("Leo", 400); Fish myFish("Algernon", 50); myLion.who(); myFish.who(); }