![]() |
|
#1
|
||||
|
||||
Need of assignment operator in case of copy constructorI always come across this statement...that you should also define assignment operator when you define copy constructor.
I don't think its any rule....can anyone elaborate on this... __________________
Gravitation is not responsible for people falling in love. -Albert Einstein |
|
#2
|
||||
|
||||
Re: Need of assignment operator in case of copy constructorHappy New Year.. (the second time!)
Quote:
And this is applicable only if you have dynamic memories associated with the class. I Hope you know the difference between assignment and initialization. Copy constructor initializes the object, whereas, assignment means making one object equal to the other. Consider this case: CPP / C++ / C Code:
So, b is initialized to 10, whereas a is assigned. This is similar to objects. Consider that there is a class A, having a character pointer. (char* is dynamically allocated!! this is the most important thing...) CPP / C++ / C Code:
Now, consider this in the main function: CPP / C++ / C Code:
So, what has happened? obj2 has called the copy constructor. If the compiler doesnt find one, it generates the default one-to-one copy constructor for you. Heck! there lies the error! Now, both obj2.x and obj1.x points to the same location!!!! To resolve this, you should explicitly define a copy constructor like this: CPP / C++ / C Code:
But what if we perform assignment? that is the case of the obj3 object. The compiler automatically generates a default operator=, and again, we get the same error. So, we have to explicitly define assignment operator like the same way we did for the copy constructor. Like this: CPP / C++ / C Code:
Hope This Helps, Best Regards, Paramesh. __________________
Don't walk in front of me, I may not follow. Don't walk behind me, I may not lead. Just walk beside me and be my friend. |
|
#3
|
||||
|
||||
Re: Need of assignment operator in case of copy constructorThanx again...I was thinking in this line but was not sure...you made it clear
__________________
Gravitation is not responsible for people falling in love. -Albert Einstein |
Recent GIDBlog
Stupid Management Policies by crystalattice
| Thread Tools | Search this Thread |
| Rate This Thread | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| How to listens to two different ports at the same time | jaro | C Programming Language | 5 | 06-Jan-2006 07:36 |
| Problem with one variable | bretter | C++ Forum | 1 | 16-May-2005 08:20 |
| Compiling Errors | ToddSAFM | C++ Forum | 22 | 18-Dec-2004 12:42 |
| there has to be a better way | dabigmooish | C++ Forum | 8 | 17-May-2004 11:24 |
| C++ file I/O | CronoX | C++ Forum | 36 | 09-Mar-2004 18:28 |
Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The