6

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?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
user997112
  • 29,025
  • 43
  • 182
  • 361
  • 1
    Which version of C++ are you using? C++11? Most likely, you should just do it where the object is constructed, not where it's declared. – David Schwartz Mar 03 '16 at 19:25
  • 1
    Possible duplicate of [C++ How to Initialize member object?](http://stackoverflow.com/questions/28436820/c-how-to-initialize-member-object) – Slava Mar 03 '16 at 19:27

1 Answers1

10

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • I remember reading somewhere that the "proper" format is `Type name { /* things */ }`, and the `=` version would be deprecated or removed. I can't find a source for that, though, so can you confirm or deny? – Nic Mar 03 '16 at 20:24