-4

now I am just really new to C++, currently I have a piece of code below:

#include <iostream>

using namespace std;

template<typename T>
class Test1
{
    public:
    Test1():var1(1) {
        cout << "Constructor1" << endl;
    }

    Test1(T a):var1(a) {
        cout << "Constructor2" << endl;
    }

    private:
    int var1;
};

template<typename T>
class Test2
{
    public:
    Test2():var2(x) {
        cout << "Constructor3" << endl;
    };

    private:
    int x;
    Test1<int> var2;
};

int main() 
{
    Test2<int> var3;
    return 0;
}

The output will just be

Constructor2
Constructor3

I wonder why the constructor2 will be called instead of constructor1, since in the class Test2, when creating the object var2, I didn't pass in any parameters, shouldn't the constructor without parameter being called?

Thank you in advance!

sunboy612
  • 13
  • 4
  • 1
    What do you mean you "didn't pass in any parameters"? The `x` part of `var2(x)` is the parameter you're passing to the constructor, to construct your `var2`. Sure, this is undefined behavior, but for other reasons. – Sam Varshavchik Apr 26 '19 at 23:44
  • @SamVarshavchik Hi, oh I didn't know that, I thought that var2(x) is a initialize list which is equal to var2 = x? – sunboy612 Apr 26 '19 at 23:50
  • No, that's a constructor invocation. Everything in the initializer list is a constructor invocation. That's what an initializer list is. – Sam Varshavchik Apr 26 '19 at 23:51
  • @SamVarshavchik Aha, now I get it, thank you! – sunboy612 Apr 26 '19 at 23:56

1 Answers1

0

The constructor for a variable is determined by its initialization. You have an initialization list on your Test2 constructor

 Test2():var2(x) {

so you have to look there for how Test2::var2 is initialized. In the initialization list, you're passing the integer x (that's not initialized to anything), so it calls the Test1 constructor that takes an integer.

If you don't explicitly initialize var2 in your initializer list (for example, if you just assign to it in the constructor body), then it will be default initialized and say "constructor 1" instead of 2

xaxxon
  • 19,189
  • 5
  • 50
  • 80