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];}elsecapacity = 0;}bool append(int v) {if (size < capacity) {list [ size++ ] = v;return true;}elsereturn false;}~Collector() {if (capacity > 0) {delete[] list;}}};int main() {// A useless Collector object of 0 capacityCollector c1;// Another Collector object, this time with a capacity of 10Collector c2(10);for(int i = 0 ; i < 15 ; i++) {cout << c2.append(i) << endl;}return 0;}
We have defined a parameterized constructor on lines ...