...

/

Constructor Delegation

Constructor Delegation

Learn how one constructor of a class can invoke another constructor of the same class

What it is

Constructor delegation is when one constructor of a class invokes another constructor of the same class. There, that’s simple enough!

How it is implemented

Let’s look at an example of how one constructor of a class may invoke another constructor of the same class.

C++
#include <iostream>
using namespace std;
class Collector {
private:
int size;
int capacity;
int* list;
public:
Collector() : Collector(0) {}
Collector(int cap) : capacity(cap), size(0) {
if (cap > 0) {
list = new int[cap];
}
else
capacity = 0;
}
bool append(int v) {
if (size < capacity) {
list [ size++ ] = v;
return true;
}
else
return false;
}
~Collector() {
if (capacity > 0) {
delete[] list;
}
}
};
int main() {
// A useless Collector object of 0 capacity
Collector c1;
// Another Collector object, this time with a capacity of 10
Collector c2(10);
for(int i = 0 ; i < 15 ; i++) {
cout << c2.append(i) << endl;
}
return 0;
}

We have defined a parameterized constructor on lines ...