C++ examples for Class:Inheritance
Constructors and Destructors during inheritance
#include <iostream> enum COLOR { RED, BLUE, WHITE, BLACK, EE, YELLOW }; class Pet /*from w w w . j a va 2 s. co m*/ { public: // constructors Pet(); ~Pet(); // accessors int getAge() const { return age; } void setAge(int newAge) { age = newAge; } int getWeight() const { return weight; } void setWeight(int newWeight) { weight = newWeight; } // other member functions void speak() const { std::cout << "Pet sound!\n"; } void sleep() const { std::cout << "shhh. I'm sleeping.\n"; } protected: int age; int weight; }; class Dog : public Pet { public: // constructors Dog(); ~Dog(); // accessors COLOR getBreed() const { return color; } void setBreed(COLOR newBreed) { color = newBreed; } // other member functions void wagTail() { std::cout << "Tail wagging ...\n"; } void begForFood() { std::cout << "Begging for food ...\n"; } private: COLOR color; }; Pet::Pet(): age(3), weight(5) { std::cout << "Pet constructor ...\n"; } Pet::~Pet() { std::cout << "Pet destructor ...\n"; } Dog::Dog(): color(RED) { std::cout << "Dog constructor ...\n"; } Dog::~Dog() { std::cout << "Dog destructor ...\n"; } int main() { Dog fido; // create a dog fido.speak(); fido.wagTail(); std::cout << "Fido is " << fido.getAge() << " years old\n"; return 0; }