lego69
lego69

Reputation: 857

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

Upvotes: 3

Views: 191

Answers (3)

GManNickG
GManNickG

Reputation: 504333

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.

Upvotes: 5

Alexander Gessler
Alexander Gessler

Reputation: 46687

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.

Upvotes: 1

Loki Astari
Loki Astari

Reputation: 264739

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&);

Upvotes: 4

Related Questions