Reputation: 1445
My concern is a default constructor and its initialisation list. In a simple case it's clear, like:
class A
{
protected:
double d1;
//classB obj1; //how to initialize this one in a default constructor?
public:
A (double x = 0.0): d1(x){} //constructor
virtual ~A(void) {};
//something
}
But how to initialize the object of classB, which has a big amount of members? Or how in general initialize in default constructor some type that has a big or unknown amount of parameters to be initialized?
Upvotes: 1
Views: 190
Reputation: 14392
If the member can be initialized by its default constructor, then it doesn't even have to be in the initialization list, because a default constructor doesn't have parameters. The default constructor will be called. Primitives don't have default constructors so they have to be in the initialization list if you want to have them initialized.
Upvotes: 1
Reputation: 45410
You could initialize obj1 in member initializer list
by calling its default constructor or other constructors
class A
{
protected:
double d1;
classB obj1;
pthread_mutex_t m_mutex;
public:
A (double x = 0.0): d1(x), obj1(), m_mutex(PTHREAD_MUTEX_INITIALIZER) {}
virtual ~A(void) {}
//something
}
if classB has big of members like you described, you may break the rule of class design - one class does one thing
. You might want to break classB into small independent classes.
Upvotes: 1
Reputation: 409166
If you want to explicitly initialize an object, just add it to the constructor initializer list:
struct Foo
{
Foo(int arg) { ... }
};
struct Bar
{
Foo foo;
Bar()
: foo(123) // Initialize `foo` with an argument
{ ... }
};
Upvotes: 1