Saturday, February 27, 2016

[C++] Why C++ 's constructor is so different?

When I first saw this :

class A{
public:
        A(int a):_a(a){};
private:
        int _a;
}

I was lost : WHAT? why not right like Java :

class A{

   private int a;
   public   A(int a){
      this.a = a;
   };

}

Now I have the answer from << Effective C++>>  :

the compiler of C++ will trait the constructor as two step :
                               it will read : A(int a) : _a() then the part in {}

 So : when we do  this : A(int a):_a(a){}; 
compiler will created an object of A, and give the value of _a as a;
But: when we do this : A(int a){ _a = a;}; 
compiler will first create the object of a and give _a a default value,  then in the {} _a will be give a value as a again!

So we saw, the first advantage is we reduce the Assignment in {} to be more efficient;
the second is that, when your member is a custom defined class,  we have no idea what value will be give to the member in the first step : 
ex:        A(B b){_b = b;} ==> when compiler create the object A(B b), what value could be given to _b? we don't know! So it's better to avoid this uncertain thing from happening.


No comments:

Post a Comment