开发者

calling constructor of a class member in constructor

开发者 https://www.devze.com 2023-04-13 02:14 出处:网络
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 constr开发者_如何学Gouctor of bar in MClass\'s construct

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 constr开发者_如何学Gouctor 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).


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.


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


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号