Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 674
user997112 Avatar asked Mar 03 '16 19:03

user997112


People also ask

Can we initialize a variable without constructor?

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.

Can we define a non default constructor without define default constructor?

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.

Should member variables be initialized?

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.

Does default constructor initialize members?

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.


1 Answers

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.

like image 118
Sergey Kalinichenko Avatar answered Oct 13 '22 01:10

Sergey Kalinichenko