calling constructor of a class member in construct

2019-01-22 19:06发布

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).

5条回答
家丑人穷心不美
2楼-- · 2019-01-22 19:47

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
   {}
};
查看更多
姐就是有狂的资本
3楼-- · 2019-01-22 19:48

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楼-- · 2019-01-22 19:51

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

查看更多
三岁会撩人
5楼-- · 2019-01-22 19:55

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.

查看更多
姐就是有狂的资本
6楼-- · 2019-01-22 20:03

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.

查看更多
登录 后发表回答