calling constructor of a class member in constructor
Solution 1
Yes, certainly you can! That's what the constructor initializer list is for. This is an essential feature that you require to initialize members that don't have default constructors, as well as constants and references:
class Foo
{
Bar x; // requires Bar::Bar(char) constructor
const int n;
double & q;
public:
Foo(double & a, char b) : x(b), n(42), q(a) { }
// ^^^^^^^^^^^^^^^^^^^
};
You further need the initializer list to specify a non-default constructor for base classes in derived class constructors.
Solution 2
Yes, you can:
#include <iostream>
using std::cout;
using std::endl;
class A{
public:
A(){
cout << "parameterless" << endl;
}
A(const char *str){
cout << "Parameter is " << str <<endl;
}
};
class B{
A _argless;
A _withArg;
public:
// note that you need not call argument-less constructor explicitly.
B(): _withArg("42"){
}
};
int main(){
B b;
return 0;
}
The output is:
parameterless
Parameter is 42
Solution 3
Through initializer list, if base class doesn't have a default constructor.
struct foo{
foo( int num )
{}
};
struct bar : foo {
bar( int x ) : foo(x)
// ^^^^^^ initializer list
{}
};
Solution 4
Like this:
class C {
int m;
public:
C(int i):
m(i + 1) {}
};
If your member constructor wants parameters, you can pass them. They can be expressions made from the class constructor parameters and already-initialized types.
Remember: members are initialized in the order they are declared in the class, not the order they appear in the initialization list.
Solution 5
Yes, you can. This is done in the initialization list of your class. For example:
class MClass
{
foo bar;
public:
MClass(): bar(bar_constructor_arguments) {};
}
This will construct bar
with the arguments passed in. Normally, the arguments will be other members of your class or arguments that were passed to your constructor. This syntax is required for any members that do not have no-argument constructors.
shampa
Updated on June 17, 2020Comments
-
shampa about 4 years
Can I call constructor of a member in my Class's constructor?
let say If I have a member
bar
of class typefoo
in my classMClass
. Can I call constructor of bar in MClass's constructor? If not, then how can I initialize my member bar?It is a problem of initializing members in composition(aggregation).
-
Jaime about 8 yearsYour comment on argument-less member constructors not having to be called explicitly is exactly what I was looking for. Thanks!
-
CCJ almost 4 yearshow come the lang spec requires an init list for constructors called with parens like this, but you can call curly initializer constructors like std::atomic_bool myBool{false} in class declarations? All I wanna do is set my atomic bool's init value without adding constructor code to my class def and for some reason I have to treat it like an array init and now my head is spinning (╯°□°)╯︵ ┻━┻