0

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

  • 1
    The first one produces no output because it doesn't even compile, much less run. There is no `a` member in `test2`, so the `:a(21)` in the member-init list will fail to compile, therefore fail to run. I don't know why you would think including `test a;` in `main` would have anything whatsoever to do with `test2`. And fyi, `test2 b();` also doesn't do what you think. That declares a *function* `b`, taking no arguments and returning a `test2` object. It does *not* create an instance of `test2` called `b`. To do that one would use `test2 b;` – WhozCraig Feb 22 '22 at 23:28
  • sry that was a mistake when copying the program my question remains the same with test a put back in the test2 object – Benjamin Tan Feb 22 '22 at 23:37
  • Oooh, I just understood the second half of your question. Thank you – Benjamin Tan Feb 22 '22 at 23:39
  • 1
    Does this answer your question: https://stackoverflow.com/questions/180172/default-constructor-with-empty-brackets – M.M Feb 22 '22 at 23:43

1 Answers1

3

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
}
Nathan Pierson
  • 5,461
  • 1
  • 12
  • 30