user997112
user997112

Reputation: 30615

How do I invoke non-default constructor for a member variable?

I have a class which is something like this:

template<int SIZE>
class MyClass{
public:
    MyClass(int a, int b){}
}

and I want another class to have an instance of MyClass:

class X{
    MyClass<10>??   // How do I pass values to constructor args a and b?
}

but I am unsure how to pass the arguments in to the two-argument constructor when declaring the object as a member variable?

Upvotes: 6

Views: 1334

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

If you are using C++11 or later, you can write

class X{
    MyClass<10> mcTen = {1, 5};
}

Demo 1.

Prior to C++11 you would need to do it in a constructor's initializer list:

class X{
    MyClass<10> mcTen;
    X() : mcTen(1, 5) {
    }
}

Demo 2.

Upvotes: 10

Related Questions