Calling a constructor within a constructor

Asked 2 years ago, Updated 2 years ago, 132 views

When I developed C#, I used it like the code below, but I wonder how I do it in C++. I wrote this() to call out the class name, but it says no Why?

class Test {
public:
    Test() {
        //DoSomething
    }
    Test(int count) : this() {
        //DoSomething
    }
    Test(int count, string name) : this(count) {
        //DoSomething
    }
};

c++ constructor

2022-09-22 22:37

1 Answers

In C++11 and above, you can call another constructor within the constructor The grammar is a bit different from C#.

class Test {
public:
    Test() {
        //DoSomething
    }
    Test(int count) : Test() {
        //DoSomething
    }
    Test(int count, string name) : Test(count){
        //DoSomething
    }
};

You can write it like this.

If you use C++03, the code above is not supported To be similar, there are the following ways:

class Test {
public:
    //Test(int) and Test(int, string) support
    Test(int count, string name=NULL){
        //DoSomething
    }
};
class Test {
public:
    Test() {
        init();
    }
    Test(int count) : Test() {
        init(count);
    }
    Test(int count, string name=NULL){
        init(count, name);
    }
private:
    void init() {}
    void init(int count) { init(); }
    void init(int count, string name) { init(count); }
};


2022-09-22 22:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.