Cpp - Constructors and Destructors in inheritance

Introduction

The following code demonstrates how constructors and destructors are called for objects belonging to derived classes.

Demo

#include <iostream> 
  
class Mammal /*from  ww w  .  j  ava 2 s  . c om*/
{ 
public: 
    // constructors 
    Mammal(); 
    ~Mammal(); 
   
    // 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 << "Mammal sound!\n"; } 
    void sleep() const { std::cout << "shhh. I'm sleeping.\n"; } 
   
protected: 
    int age; 
    int weight; 
}; 
   
class Dog : public Mammal 
{ 
public: 
    // constructors 
    Dog(); 
    ~Dog(); 
   
    // accessors 
    int getBreed() const { return breed; } 
    void setBreed(int newBreed) { breed = newBreed; } 
   
    void wagTail() { std::cout << "Tail wagging ...\n"; } 
    void begForFood() { std::cout << "Begging for food ...\n"; } 
   
private: 
    int breed;  
}; 
   
Mammal::Mammal(): 
age(3), 
weight(5) 
{ 
    std::cout << "Mammal constructor ...\n"; 
} 
   
Mammal::~Mammal() 
{ 
    std::cout << "Mammal destructor ...\n"; 
} 
   
Dog::Dog(): 
breed(2) 
{ 
    std::cout << "Dog constructor ...\n"; 
} 
   
Dog::~Dog() 
{ 
    std::cout << "Dog destructor ...\n"; 
} 
   
int main() 
{ 
    Dog my_dog2; // create a dog 
    my_dog2.speak(); 
    my_dog2.wagTail(); 
    std::cout << "Fido is " << my_dog2.getAge() << " years old\n"; 
    return 0; 
}

Result

Related Topic