copy constructor and assignment opearator

Posted on 2004-09-09
Last Modified: 2010-04-01
Compiler give copy constructor and constructor implicitly. then what the need of declare copy constructor explicitly.
Suppose we have three different scnerio
void func(int ii);
void func(int &ii)
void func(int *ii)
In which case copy constructor call and why.
Please also tell me the difference between Assignment operator and copy constructor.
How the Shallow copy and bit copy work.
Question by:Mtnl

Expert Comment

ID: 12023714
you need a copy ctor when you have pointer members in your class. the default copy ctor provided by the compiler clones your variable. if you are dealing with dynamic mem allocation this could and in most cases would cause problems. here's an example

class class1{
  int *ptr;
  int sz;

int main(){
  class1 c1, c2; = 16;
  c1.ptr = new int[];
  c2 = c1;
  delete[] c1.ptr;
  return 0;
c2.ptr is now pointing to a location in heap which is no longer yours. if you try to access it a few lines later you would probably get garbage or a crashed program. in such a case you would want to write a copy ctor that would: (1) copy sz variable, (2) allocate new memory, (3) and use a loop to copy the array. and don't forget to write the destructor or there would be memory leaks.


Accepted Solution

pankajtiwary earned 50 total points
ID: 12023802
There are three things constructor, copy constructor and assignment operator. You need to remember the following things.

1. The constructor is called whenever you are trying to create an object from *scratch*. That means you are going to create a fresh new piece of something. Then comes the default constructor. A default constructor is something that can be called without any arguments. This can be of 2 types. Either the argument is not necessary at all. This is of the form Myclass(). The other form may be that the arguments are necessary but you have provided the constructor woth defaulkt parameters. This is of the form MyClass(int a=0, int b=0). Both of these are default constructor. The rule is if you don't provide any *constructor* for the class, the compiler will create one for you. That will be of the form MyClass(). But if you define even one constructor, the comiler won't create any for you.


Myclass a;
Myclass b(1,2);

These both lines will call the constructor.

2. The copy constrcutor is called whenever you are trying to create a new object from an existing one or you need to create a copy of an object.

MyClass c = b;

The above statement will call the copy constructor because c is being created from b. Also if you are passing or returning an object by value then also a copy of the object is created hence copy constructor is called.

3. The assignment operator is called when you have 2 fully made objects and you want to assign one to the other.

b = a;

This will invoke the assignment operator.

Just liek default constructor the compiler provides one copy constructor which does nothing but a bitwise copy. If you want your control over the copying process you need to define your own copy constructor. Your copy constructor will simulate the bahaviour of creating a fresh new object from the existing one.

Hope this helps.

Author Comment

ID: 12027277
thanks pankaj
As you said if you not specify any copy constructor, compiler will give copy constructor for you.If compiler is giving implicitly, what the need of define copy constructor explicitly. And plz also discuss this three case......
void func(int ii);
void func(int &ii)
void func(int *ii)
 when copyconstructor or constructor  will called and why.

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.


Expert Comment

ID: 12029517

  You need to write your own copy constructor if the compiler generated one doesn't do the right thing. Take jkshukla's example.
class A{
  int *ptr;
  int sz;
   delete ptr;

Now suppose you have code like this.
void Foo()
A objClass1;
       A objClass2 = objClass1;

objClass2 is copy constructed and because you've not defined a copy constructor, the compiler generated one does a bitwise copy, it copies values of ptr and sz from objClass1 to objClass2.
Now when objClass2 goes out of scope, its destructor gets called, which deletes ptr. But objClass1 is still alive and might access ptr. Deferencing a deleted pointer will lead to undefined behaviour, as you surely must be knowing.

So what you do is define a copy constructor yourself that does the right thing. The easiest thing would be to allocate memory and copy contents.

void func(int ii);
void func(int &ii)
void func(int *ii)

Copy constructors are not involved here, as they are only relevant for structs/classes. For those two, passing by value will involve copy construction, passing by reference/pointer will not.

Author Comment

ID: 12033542
Thanks Jksukla and pankaj.

Author Comment

ID: 12033547
and thanks to senthil kumar also

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now