Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading