0

Possible Duplicate:
Is there a difference in C++ between copy initialization and direct initialization?

Class A
{
public:
   //some member function call
private:
   int x;
   char a;
};
int main()
{
   A a;
   A b;
}

Hi can You tell me the Difference's in Between these when I call or initialize the objects of above class as

A a(b);
A a=b;
a=b;
Community
  • 1
  • 1
Avinash Gopal
  • 101
  • 1
  • 1
  • 5

3 Answers3

3

The first 2 lines calls the copy constructor because the objects are being constructed. The last line will call the equals operator to perform the assignment.

Superman
  • 3,027
  • 1
  • 15
  • 10
2
A a(b);
A a = b;

These use the implicitly generated copy constructor.

a = b;

This one uses the assignment operator, and it is not an initialization, since it does not create an A object: it just gives a new value to an existing one.

The copy constructor would have a signature such as

A(const A&);

and the assignment operator

A& operator=(const A&);

Since your class doesn't provide these, the compiler synthesizes them and just copies the data members.

Emilio Garavaglia
  • 20,229
  • 2
  • 46
  • 63
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

Since your class doesnt have any explicit copy constructor all of the above statements results in shallow copy.

If you have declared a copy constructor and overloaded the = operator then

A a(b) and A a= b will result in calling the copy constructor and

a= b will result in calling the = overloaded operator

Read this for more understanding

Jeeva
  • 4,585
  • 2
  • 32
  • 56