Calling Specific Base constructors

Sometimes when you write a constructor, you would like to pass some of the parameters to a base constructor.

Example:

class Person {
private:
  Date *birthday;
public:
  Person(Date *bd);
};
class Student : public Student {
private:
  School *attends;
public:
  Student(Date *birth, School *sch);
};

In this case, the "bd" parameter for the school constructor could just be passed on to the parent constructor. And we can do that by calling the parent constructor:

Student::Student(Date *birth, School *sch) : Person(birth) {
  this->school = sch;
}

Pros and Cons:

  • Works only if we can put the parameters for the superconstructor within one expression

  • You don't have to provide a default constructor in your superclass

  • You can keep your attribute private

Note: If you're in multiple inheritance, you can call multiple superconstructors by separating them with a comma. E.g. : Person(birth), OtherConstructor(params).

Practice: Assume these two given class definitions. Implement both constructors, with one calling its superconstructor.

class Computer
{
private:
  int cpuSpeed;
public:
  Computer(int cpuSpeed);
};
class Laptop : public Computer
{
private:
  int batteryLife;
public:
  Laptop(int cpuSpeed, int batteryLife);
};
Computer::Computer(int cpuSpeed)
{
  this->cpuSpeed = cpuSpeed;
}
Laptop::Laptop(int cpuSpeed, int bl) : Computer(cpuSpeed)
{
  batteryLife = bl;
}