开发者

question about copy constructor

I have this class:

class A {
private:
 int player;
public:
 A(int initPlayer =开发者_运维技巧 0);
 A(const A&);
 A& operator=(const A&);
 ~A();
 void foo() const;
};

and I have function which contains this row:

 A *pa1 = new A(a2);

can somebody please explain what exactly is going on, when I call A(a2) compiler calls copy constructor or constructor, thanks in advance


Assuming a2 is an instance of A, this calls the copy constructor.

It will call operator new to get dynamic memory for the object, then it will copy-construct a new object into the memory, then return a pointer to that memory.


When you call new A(a2);

It will call one of the constructors.
Which one it calls will depend on the type of a2.

If a2 is an int then the default constructor is called.

A::A(int initPlayer = 0);

If a2 is an object of type A then the copy constructor will be called.

A::A(const A&);


This depends on the data type of a2. If it is int or a type that can implicitly be converted to int, the default c'tor (A(int player=0)) will be called, if a2 is an instance of A or an type that can implicitly be converted to A (i.e. instance of a sub-class) the copy c'tor will be called.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜