2

Comming from Java, I have difficulty with the code below. In my understanding b is just declared on line 3 but not instantiated.

What would be the text book way of creating an instance of B in class A?

class A {
  private:
    B b;
  public:
    A() { 
      //instantiate b here?
    }
};

Edit: What if B does not have a default constructor?

user695652
  • 4,105
  • 7
  • 40
  • 58

4 Answers4

9

You could explicitly initialize b in A's constructor's initialization list, for example

class A {
  B b; // private
 public:
  A : b() {} // the compiler provides the equivalent of this if you don't
}; 

However, b would get instantiated automatically anyway. The above makes sense if you need to build a B with a non-default constructor, or if B cannot be default initialized:

class A {
  B b; // private
 public:
  A : b(someParam) {}
};

It may be impossible to correctly initialize in the constructor's initialization list, in which case an assignment can be done in the body of the constructor:

class A {
  B b; // private
 public:
  A {
    b = somethingComplicated...; // assigns new value to default constructed B.
  }
};
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
0

You have created an instance of b in line 3. This line is enough so that B's constructor is called. If you have code like this

class A {
  private:
    B *b;
  public:
    A() { 
      //instantiate b here?
    }
};

then it would make sense to instantiate b in A's constructor like

A()
 { 
    b = new B();
 }
Jeeva
  • 4,585
  • 2
  • 32
  • 56
  • But this would be bad code. Never mind that raw pointers should never own memory, you should use the initialiser list rather than assignments in the constructor’s body. – Konrad Rudolph Jul 24 '12 at 13:12
0

The correct phase your looking for is "C++ initialization list". This initialization list is called/initialized before the constructor is called

In case of Default constructor, compiler equvalient constructor will be A() : B() {}

A very good reference http://www.cprogramming.com/tutorial/initialization-lists-c++.html

Rituparna Kashyap
  • 1,497
  • 13
  • 19
0

At line 3, it is simply a declaration of B. However somewhere in your code where you have:

A a;

or

A a();

This calls the constructor of A. The internal b private member is full or garbage, as in not initialized. You are correct in that you can and probably should initialize member variable during construction where possible. There are two ways to do this:

A () 
{
   b = B ();
}

Like you said:

or

A () : b (B())
{
}

The second version (initialization list) is slightly more efficient since it creates the new B object directly inside b. Whereas the first version creates a temporary and then moves that into b. This is the case when you initialize members from passed in parameters anyway (for non built in types). I'm making an assumption its the same in this case, but someone will be able to clarify.

Science_Fiction
  • 3,403
  • 23
  • 27