1

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!

6
  • godbolt.org/z/GzYymO here you have the correct syntax. Commented Apr 9, 2019 at 3:26
  • 4
    C++11 - Delegating Constructors.. those are the keywords you can search for.. stackoverflow.com/q/13961037/1462718 Commented Apr 9, 2019 at 3: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. Commented Apr 9, 2019 at 3:27
  • Note also you're not initializing age on the default constructor; that goes away if you put int age= 0; Commented Apr 9, 2019 at 3:28
  • godbolt.org/z/k1QdTD better Commented Apr 9, 2019 at 3:31

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.