Delegating Constructors

In this lesson, you will learn two techniques from C++11 that allow us to reuse existing code from constructors.

We'll cover the following...

Delegating constructors

Sometimes, when your class contains many data members and several constructors, it might be convenient to reuse their initialization code.

Fortunately, since C++11, you can use delegating constructors, which can call other constructors.

Let’s look at an example:

Press + to interact
#include <iostream>
#include <string>
#include <exception>
class Car {
public:
Car() : Car(0, 0.0, "default") { }
Car(int seats, const std::string& name) : Car(seats, 0.0, name) { }
Car(int seats, double maxVel, const std::string& name)
: seats_(seats)
, maxVelocity_(maxVel)
, name_(name)
{
VerifyData();
}
void VerifyData() const {
if (seats_ < 0 || seats_ > 1000)
throw std::runtime_error("wrong number of seats");
}
// getters and setters:
int GetSeats() const { return seats_; }
double GetMaxVelocity() const { return maxVelocity_; }
std::string GetName() const { return name_; }
private:
int seats_;
double maxVelocity_;
std::string name_;
};
int main() {
try {
Car regularCar{4, "a common car"};
std::cout << "name: " << regularCar.GetName() << " created... \n";
Car oldCar{30000, 42.5, "super fast but old"};
std::cout << "name: " << oldCar.GetName() << " created... \n";
}
catch (const std::exception& e) {
std::cout << "cannot create: " << e.what() << '\n';
}
}

In the above example, we declare three constructors, and two of them call the “primary” one, which performs the core job. Inside this main constructor, we not only initialize ...