-3
#include <iostream>
using namespace std;
class A{
public:
 int a;
  A() {a=0;}
  A(int b) {a=b+1;}
};
class B{
public:
   A a;
   B():a(0) {}


};

int main(void) {
    B *b = new B();
    cout<<b->a.a<<endl;
    return 0;
}

I replaced B():a(0) {} by B() {A(0)} and output changed from 1 to 0. I am wondering what's the difference between them?

1 Answers1

3

B() : a(0) {} explicitly initializes the member B::a with the value 0. This is an example of a member initializer list. Basically, a(0) in this context calls a's constructor with the argument 0, which calls A::A(int), which, by your implementation, adds 1 to the argument and assigns the result to A::a. Thus in the first case, b->a.a == 1.

On the other hand, B() {A(0);} default-initializes B::a (because A has a default constructor) and creates a nameless local temporary object A(0); which is destroyed immediately without changing anything. It is functionally equivalent to B(){}, which is does nothing at all. You can omit this trivial constructor because the compiler can implicitly generate it for you. See special member functions for more information on how this works and under what conditions. Thus in the second case, you are calling the default constructor, which sets b->a.a == 0.

alter_igel
  • 6,899
  • 3
  • 21
  • 40