calling constructor of a class member in construct

2019-01-22 19:58发布

问题:

Can I call constructor of a member in my Class's constructor?

let say If I have a member bar of class type foo in my class MClass. 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).

回答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.



回答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

View this on ideone.com



回答3:

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.



回答4:

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


回答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.