Copy Constr vs = overloading

Copy constructor allows creation of new object from an existing one.
Hence in the following cases copy contr wud be called:
1)Obj o1(o);
2)Obj o2 = o;

(o is also an oject of Obj)

But the statement 2 can also be realised by overloading =operator.
So what will happen if i have both declared:copy constr & =operator.And what is the difference??
I don't understand your question, generally you have:

1
2
3
4
5
6
class Foo {
  public:
       Foo();
       Foo(const Foo& obj);  // Copy constructor
       Foo& operator = (const Foo& rhs); // Assignment operator
};


1. Foo x0; // Default constructor
2. Foo x1(x0); // copy constructor
3. Foo x2 = x1; // copy constructor. if you declare the copy constructor explicit this will not work anymore.
4. x2 = x0; // Assignment operator.
The copy constructor is ONLY used in the creation of new objects so Obj o1(o); is equivalent to Obj o2 = o;, however, neither are equivalent to:

1
2
3
4
Obj o1();
Obj o2();
//do stuff
o1 = o2;


As you are assigning the object to a pre-existing object.

In summary:
-copy constructor is used for new objects.
-assignment operator is used for existing objects.

Hope that clears things up.
1
2
3
4
Obj o1();
Obj o2();
//do stuff
o1 = o2;


Of course, this will not compile because o1 and o2 are defined as functions and not as objects.

;P
In the case of

Obj o2 = o;, the compiler will use the copy constructor (even if the operator= function exists).
Thanks all...it a lot more clear now.
Just a few more clarification:
For the class:
1
2
3
4
5
6
class Foo {
  public:
       Foo();
       Foo(const Foo& obj);  // Copy constructor
       Foo& operator = (const Foo& rhs); // Assignment operator
};



1. Foo x0; // Default constructor
2. Foo x1(x0); // copy constructor
3. Foo x2 = x1; // copy constructor.
4. x2 = x0; // Assignment operator.

What if I have not overloaded = operator for the class Foo.
Will statement No.4 work?? If yes,how?
If you do not define an assignment operator, the compiler will generate a default one. The default one does a member by member copy, which is ok for classes that contain only POD member data. One red flag that the compiler-generated one is not adequate is if the class contains one or more pointers. The same goes for the copy constructor.
Last edited on
@moorecm :That was the missing links that was causing me all the confusion ..
Thanks ..
Topic archived. No new replies allowed.