Can I call a constructor from another constructor (do constructor chaining) in C++?

前端 未结 15 2497
暖寄归人
暖寄归人 2020-11-22 01:27

As a C# developer I\'m used to running through constructors:

class Test {
    public Test() {
        DoSomething();         


        
15条回答
  •  轮回少年
    2020-11-22 01:53

    Would be more easy to test, than decide :) Try this:

    #include 
    
    class A {
    public:
        A( int a) : m_a(a) {
            std::cout << "A::Ctor" << std::endl;    
        }
        ~A() {
            std::cout << "A::dtor" << std::endl;    
        }
    public:
        int m_a;
    };
    
    class B : public A {
    public:
        B( int a, int b) : m_b(b), A(a) {}
    public:
        int m_b;
    };
    
    int main() {
        B b(9, 6);
        std::cout << "Test constructor delegation a = " << b.m_a << "; b = " << b.m_b << std::endl;    
        return 0;
    }
    

    and compile it with 98 std: g++ main.cpp -std=c++98 -o test_1

    you will see:

    A::Ctor
    Test constructor delegation a = 9; b = 6
    A::dtor
    

    so :)

提交回复
热议问题