简体   繁体   中英

c++ class in a class default constructor

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?

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.

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
    { ... }
};

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM