2

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!

Gimcrack
  • 83
  • 6
  • https://godbolt.org/z/GzYymO here you have the correct syntax. – Mirko Apr 09 '19 at 03:26
  • 4
    C++11 - Delegating Constructors.. those are the keywords you can search for.. https://stackoverflow.com/q/13961037/1462718 – Brandon Apr 09 '19 at 03:26
  • BTW there's no need for `this->` in `this->createdAt`. `createdAt= 0;` works just fine. On most modern compilers you can put `int createdAt= 0;` so there's no need for that either. – Mirko Apr 09 '19 at 03:27
  • Note also you're not initializing age on the default constructor; that goes away if you put `int age= 0;` – Mirko Apr 09 '19 at 03:28
  • https://godbolt.org/z/k1QdTD better – Mirko Apr 09 '19 at 03:31
  • @mirko, thanks for your replies. I intentionally wasn't initializing `age`. This is just a test program for myself. Thanks for your concern though! – Gimcrack Apr 09 '19 at 03:32

1 Answers1

3

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;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Shoyeb Sheikh
  • 2,659
  • 2
  • 10
  • 19