Home > Net >  Why does a Member initialized list for a default constructor in a composite class not call the membe
Why does a Member initialized list for a default constructor in a composite class not call the membe

Time:02-23

The Member initialized list for a default constructor in a composite class does not call the member object constructor.

#include <iostream>
struct test{
    test(){
        std::cout << "defualt is called" << std::endl;
    }
    test(int num){
        std::cout <<"parameter is called" << std::endl;
    }
};
struct test2{
    test a;
    test2():a(21){}
};
int main(){

    test2 b();
}

Nothing is outputted, but if I change the default constructor in the composite class to a parameterized one then it works as expected

#include <iostream>
struct test{
    test(){
        std::cout << "defualt is called" << std::endl;
    }
    test(int num){
        std::cout <<"parameter is called" << std::endl;
    }
};
struct test2{
    test a;
    test2(int num):a(21){}
};
int main(){
    test2 b(4);
}

output is: parameter is called

CodePudding user response:

test2 b(); is a function declaration, not a variable declaration. It declares a function named b that takes no arguments and returns a test2. Either of the following would produce a test2 variable that uses the default constructor:

int main(){
    test2 b; // No parentheses at all
}
int main(){
    test2 b{}; // Curly braces instead of parentheses
}
  • Related