Reputation: 83
When overloading constructors, is it possible to have a non-default constructor call the default constructor, so that I am not copy-pasting the code from the default constructor into any later non-default constructors? OR what is the reason for not allowing this functionality?
Here's my code:
class Test{
private:
int age;
int createdAt;
public:
//Here is the defualt constructor.
Test(){
this->createdAt = 0;
};
//Non-default constructor calling default constructor.
Test(int age){
this->Test(); //Here, call default constructor.
this->age = age;
};
};
Do note that this code throws the compiler error "Invalid use of Test::Test", so I'm obviously doing something incorrect.
Thanks for your time!
Upvotes: 2
Views: 1379
Reputation: 2866
Yes it is possible with the help of delegating constructor. This feature, called Constructor Delegation, was introduced in C++ 11. Take a look at this,
#include<iostream>
using namespace std;
class Test{
private:
int age;
int createdAt;
public:
//Here is the defualt constructor.
Test(){
createdAt = 0;
};
//Non-default constructor calling default constructor.
Test(int age): Test(){ // delegating constructor
this->age = age;
};
int getAge(){
return age;
}
int getCreatedAt(){
return createdAt;
}
};
int main(int argc, char *argv[]) {
Test t(28);
cout << t.getCreatedAt() << "\n";
cout << t.getAge() << "\n";
return 0;
}
Upvotes: 3