Cpp - Passing Arguments to Base Constructors

Introduction

Base class initialization can be performed during class initialization by writing the base class name followed by the parameters expected by the base class.

Demo

#include <iostream> 
class Mammal//from  ww w . ja v  a2  s.  com
{
public:
  // constructors 
  Mammal();
  Mammal(int age);
  ~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(int age);
  Dog(int age, int weight);
  Dog(int age, int weight, int breed);
  ~Dog();

  // accessors 
  int getBreed() const { return breed; }
  void setBreed(int newBreed) { breed = newBreed; }

  // other member functions 
  void wagTail() { std::cout << "Tail wagging ...\n"; }
  void begForFood() { std::cout << "Begging for food ...\n"; }

private:
  int breed;
};

Mammal::Mammal() :
  age(1),
  weight(5)
{
  std::cout << "Mammal constructor ...\n";
}

Mammal::Mammal(int age) :
  age(age),
  weight(5)
{
  std::cout << "Mammal(int) constructor ...\n";
}

Mammal::~Mammal()
{
  std::cout << "Mammal destructor ...\n";
}

Dog::Dog() :
  Mammal(),
  breed(2)
{
  std::cout << "Dog constructor ...\n";
}

Dog::Dog(int age) :
  Mammal(age),
  breed(2)
{
  std::cout << "Dog(int) constructor ...\n";
}

Dog::Dog(int age, int newWeight) :
  Mammal(age),
  breed(2)
{
  weight = newWeight;
  std::cout << "Dog(int, int) constructor ...\n";
}

Dog::Dog(int age, int newWeight, int breed) :
  Mammal(age),
  breed(breed)
{
  weight = newWeight;
  std::cout << "Dog(int, int, int) constructor ...\n";
}


Dog::~Dog()
{
  std::cout << "Dog destructor ...\n";
}

int main()
{
  Dog my_dog2;
  Dog rover(5);
  Dog buster(6, 8);
  Dog my_dog(3, 2);
  Dog dobbie(4, 20, 3);
  my_dog2.speak();
  rover.wagTail();
  std::cout << "Yorkie is " << my_dog.getAge() << " years old\n";
  std::cout << "Dobbie weighs " << dobbie.getWeight() << " pounds\n";
  return 0;
}

Result

Related Topic