Click here to Skip to main content
15,884,023 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi All,

I understand that when i am going to initialize the existing object to newly created object copy constructor is called.

Please find the below example.



C#
#include<iostream>

using namespace std;

class Base
{
    int* m;
    public:
    Base(int p)
    {
      m = new int(p);
    }
    Base(const Base& obj)
    {
      m = new int(*obj.m);
    }
    Base operator=(const Base& obj1)
    {
        m = new int(*obj1.m);
    }
    ~Base()
    {
      delete m;
    }
};

int main()
{

    Base b(10);
    Base a = b;
    b = a;

    return 0;
}



here why should i do Base a = b; or when the condition will occur? or where should i call?

anybody can clarify?.

Thanks and Regards,
Ranjith kumar.S
Posted
Updated 12-Nov-13 20:00pm
v2
Comments
Sergey Alexandrovich Kryukov 13-Nov-13 1:43am    
What condition? The question does not make much sense.
—SA
ranjithkumar81 13-Nov-13 1:45am    
which scenario should i use Base a = b;
WuRunZhe 13-Nov-13 5:32am    
What do you mean? What is your problem?

Not a correct question. You should not do anything. This is just the artifact of the test code you show intended to illustrate of the copy constructor and custom operator functionality. I would advise you to use it in the following way: run it all under a debugger step-by-step, to see what parts of code are called and when. (But first, it will need a fix, see below :-)

So, if you still did not get it, the second line of main() is initialization of a, it calls the copy constructor.
The third line calls '=' operator. That's all.

Generally, your problem is your approach to learning and asking questions. The response "ask the person who gave you this code sample" would be quite a legitimate answer. A reasonable question would be also "what would you suggest?". Not declaring a as a variable of the type Base? But then it would not compile. In essence, the question "why" does not always make certain sense. You would need to explain your concern. And finally, you can reasonably ask a question about problems with your own code, but as to the code you found somewhere… why would we even consider it? One can find too many pieces of trash on the Web, so what? Why responding to it? Why do I mention trash? Well, because your code sample won't even compile: the '=' operator, as it is defined, requires return, which is missing. Did you mean to return this?

Many years ago, great American American popular mathematics and science writer Martin Garner taught all us one great idea. Suppose a child asks you: "why all bodies fall on the ground". Gardner reasonably proved to us that the answer "this is just because things work this way" is no less valid than all the considerations of gravitation, or, say, curvature of space-time. Can you see the point?

—SA
 
Share this answer
 
v2
I understand you want to know the difference between using an initialization like
C++
Base a = b;

and an assignement like
C++
b = a;

Both will have the effect of transporting the object on the right side to the left side. BUT: When initializing an object it is not necessary to release any memory or other resources that the object might have acquired. Thus, the execution of the copy constructor is in general a little faster than an assignment.

In an assignment operation, all resources acquired by the object must first be released before the right hand object can be copied over. And that is what you forgot in the implementation of your assignment operation:
C++
Base operator=(const Base& obj1)
{
    m = new int(*obj1.m); // error: whatever memory had been pointed to by m
                          // will be lost
}

You would have to change it to:
C++
Base operator=(const Base& obj1)
{
    delete m;
    m = new int(*obj1.m); // error: whatever memory had been pointed to by m
                          // will be lost
}

and that explains the major difference between initialization and assignment.
 
Share this answer
 
Comments
ProgramCpp 22-Nov-13 4:51am    
y not just copy the value in case of assignment operator.

Base& operator=(const Base& obj1)
{
*m = *(obj1.m);
return *this;
}
You use class_name a = b; or class_name a(b); whenever you want to initialise an object with a copy of another. That's it, just about everything is implied by the name!
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 13-Nov-13 2:14am    
You probably missed that the sample code shown won't even compile... Please see my answer.
—SA
int main()
{
 
    Base b(10);
    Base a = b;
    b = a;
 
    return 0;
}


Ok, First thing to keep in mind. When ever you are creating an object a constructor need to be called.

This can be:
1. Default Constructor
2. Parametrised Constructor or
3. Copy constructor

so:

C++
Base b(10); //Object doesn't exist. Need to call a Constructor. Will call your parametrised constructor


C++
Base a = b; //object "a", doesn't exist. So a constructor needs to be called. So here the most matching constructor is your copy constuctor. So it will be called.


However,
C++
b = a; // both b and a have already been created, so no need to call any constructor. Hence your assingment operator will be called.


I hope this clears things up
 
Share this answer
 
Comments
ranjithkumar81 14-Nov-13 4:20am    
Base(const Base& obj)
{
m = new int(*obj.m);
}



Here while creating copy constructor , why should i pass reference and why can not value?
and what is the necessary of const in copy constructor?
ProgramCpp 22-Nov-13 5:31am    
reference to avoid creation of a copy of the parameter passed and "const" to make sure the parameter passed isnt modified.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900