Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I don't want to use the default constructor so I implement mine

class A
{
  public:
     A(int&i);
     A& operator=(const A& a);
     A(const A&a);
};

But in class B

class B
{
   A a;
   public:
     B(const A&a){this->a=a;}
}

Then the error:

no appropriate default constructor of A found.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
726 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use a constructor initialization list, so the member a is initialized via the copy constructor:

B(const A&a):a(a){}

If you don't use a constructor initialization list, then the compiler first tries to initialize A a;, and only after assigns the other a to it. However, the first initialization fails because there is no default constructor provided. In general, it is recommended to always using the constructor initialization list when initializing members. In this way, instead of calling one constructor + one assignment operator, you only call the copy constructor.

I suggest changing the name of the member from a to e.g. _a, so the code becomes a bit more clear.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...