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?
Even if you don't have a constructor in your class, you can still create objects. Example: class A{ } class B{ public static void main(String[] args){ A x = new A(); B y = new B(); //both are valid and the code will compile.
Without initializing an object we can't use its properties. But there is no need to define or declare a default constructor in Java. The compiler implicitly add a default constructor in the program if we have not declared or defined it. Save this answer.
You should always initialize native variables, especially if they are class member variables. Class variables, on the other hand, should have a constructor defined that will initialize its state properly, so you do not always have to initialize them.
Default constructors are one of the special member functions. If no constructors are declared in a class, the compiler provides an implicit inline default constructor. If you rely on an implicit default constructor, be sure to initialize members in the class definition, as shown in the previous example.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With