简体   繁体   中英

Using default constructor in non-default constructor

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!

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM