473,396 Members | 2,036 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

overloaded assignment operator and copy constructor.

Hi Everyone,

I was just wondering, about the overloaded assignment operator for
user defined objects. It is used to make sure that the following works
properly,

obj1 = obj;

so the overloaded operator function performs the necessary copy of
obj's member in to obj1. Can't the same be done using copy
constructor? If so, then what is the difference between both the
mechanisms.

Thanks in advance!!!

Aug 22 '07 #1
5 2257
On Aug 22, 3:56 pm, sam_...@yahoo.co.in wrote:
Hi Everyone,

I was just wondering, about the overloaded assignment operator for
user defined objects. It is used to make sure that the following works
properly,

obj1 = obj;

so the overloaded operator function performs the necessary copy of
obj's member in to obj1. Can't the same be done using copy
constructor? If so, then what is the difference between both the
mechanisms.

Thanks in advance!!!
assignment operator is "assignment operator", copy constructor is a
"constructor". both have different semantics.

class X { };

int main()
{
X x;
X y = x; //invokes copy constructor, since y is getting constructed
y = x; // invokes copy assignment operator, since y already exists
and is merely getting assigned.
}

-N

Aug 22 '07 #2
In message <11*********************@q3g2000prf.googlegroups.c om>,
Neelesh Bodas <ne***********@gmail.comwrites
>On Aug 22, 3:56 pm, sam_...@yahoo.co.in wrote:
>Hi Everyone,

I was just wondering, about the overloaded assignment operator for
user defined objects. It is used to make sure that the following works
properly,

obj1 = obj;

so the overloaded operator function performs the necessary copy of
obj's member in to obj1. Can't the same be done using copy
constructor? If so, then what is the difference between both the
mechanisms.

Thanks in advance!!!

assignment operator is "assignment operator", copy constructor is a
"constructor". both have different semantics.

class X { };

int main()
{
X x;
X y = x; //invokes copy constructor, since y is getting constructed
y = x; // invokes copy assignment operator, since y already exists
and is merely getting assigned.
Not always "merely". Assignment also involves disposing of the previous
contents.
>}

-N
--
Richard Herring
Aug 22 '07 #3
On Aug 22, 1:56 pm, sam_...@yahoo.co.in wrote:
Hi Everyone,

I was just wondering, about the overloaded assignment operator for
user defined objects. It is used to make sure that the following works
properly,

obj1 = obj;

so the overloaded operator function performs the necessary copy of
obj's member in to obj1. Can't the same be done using copy
constructor? If so, then what is the difference between both the
mechanisms.

Thanks in advance!!!
constructors are -say philosofically- invoked on newly allocated
objects who do not carry any valid data, but assignment happens for
previously constructed objects that contain valid -though not
interesting - data. Thus an assignment operator might need to get read
of rubish data in some cases -often pointeriod types - while
constructors generally need not destroy anything before copying
existing data to a new location.

regards,
FM.

Aug 22 '07 #4
MyType& operator=( MyType const& other )
{
MyType temporary( other ); // Copy construct into new instance.
swap( other ); // Swap contents with new instance.

Sorry, I cannot understand what does it mean swap?

For example, while cannot we do:

MyType& operator=(MyType const& other)
{
swap(other);
return *this;
}

Please, can you describe (for example) such situation:

class MyClass
{
int* pArray; /pointer to array, need allocation memory
/...
}

what's copy constructor, operator= and swap?

Aug 24 '07 #5
On Aug 25, 12:19 am, alexdem...@gmail.com wrote:
MyType& operator=( MyType const& other )
{
MyType temporary( other ); // Copy construct into new instance.
swap( other ); // Swap contents with new instance.

Sorry, I cannot understand what does it mean swap?

For example, while cannot we do:

MyType& operator=(MyType const& other)
{
swap(other);
return *this;

}

Please, can you describe (for example) such situation:

class MyClass
{
int* pArray; /pointer to array, need allocation memory
/...

}

what's copy constructor, operator= and swap?
The term 'swap' means exchanging the values of two objects.A general
solution for swappig two objects is the famuse triple assign method:

temp=other;
other=me;
me=temp;

but in some cases there exists a short cut and we do not need to pay
that much for the swap;In such cases a swap is normally performed much
faster and easier than an assignment ,and assignment is defined in
terms of swap rather than the vice versa.(pointeroids , string &
reference counting are best examples .):

struct my_string{
public:
my_string():str(null),sz(0){};
my_string(const char *const s){/* build from null-terminated c-
style string and literals*/
sz=strlen(s);
str=new char[sz];
memcpy(str,s,sz);
};
my_string(my_string& s):str(new char[s.sz]),sz(s.sz)
{memcpy(str,s.str,sz);};

bool swap(my_string& right){
if (right==*this) return false;

//swap str:
char* temp=str;
str=right.str;
right.str=temp;

//swap sz:
sz^=right.sz;
right.sz^=sz;
sz^=right.sz;

return true;
};

bool operator==(const my_string& right){
if(sz!=right.sz) return false;
return 0==memcmp(str,right.str,sz);
};

const my_string& operator=(my_string other){
swap(other);
return *this;
};

~my_string(){delete[] str;};

private:
char* str;
size_t sz;
....//concate , find , cstr , size ... etc
};

this is not the best approach to design strings but it shares the
common swap/copy/assign method of dynamic memory management with
better solutions.If you defined swap in terms of assignment,allocation/
deallocation(new/delete) of memory would happen three times per
swap.But now swap needs no allocation/deallocation and as you can
see,assignment needs exert a deallocation in either case (destruction
of auto variable or explicit delete).

regards,
FM

Aug 29 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Nitin Bhardwaj | last post by:
Thanx in advance for the response... I wanna enquire ( as it is asked many a times in Interviews that i face as an Engg PostGraduate ) about the overloading capability of the C++ Language. ...
5
by: Andy Jarrell | last post by:
I'm trying to inherit from a specific class that has an overloaded operator. The problem I'm getting is that certain overloaded operators don't seem to come with the inheritance. For example: ...
9
by: August1 | last post by:
Below are the declaration for an overloaded assignment operator in an interface file in addition to the implementation file definition of the function. What would be an appropriate if condition to...
4
by: August1 | last post by:
I've written an interface and implementation file along with a client source file that allows the use of an overloaded subtraction operator. However, when using the program, I'm running into a...
1
by: masood.iqbal | last post by:
I have a few questions regarding overloaded typecast operators and copy constructors that I would like an answer for. Thanks in advance. Masood (1) In some examples that I have seen...
2
by: Tony Johansson | last post by:
Hello Experts!! I have two small classes called Intvektor and Matris shown at the bottom and a main. Class Intvektor will create a one dimension array of integer by allocate memory dynamically...
5
by: raylopez99 | last post by:
I need an example of a managed overloaded assignment operator for a reference class, so I can equate two classes A1 and A2, say called ARefClass, in this manner: A1=A2;. For some strange reason...
9
by: itdevries | last post by:
Hi, I've ran into some trouble with an overloaded + operator, maybe someone can give me some hints what to look out for. I've got my own custom vector class, as a part of that I've overloaded...
3
by: jr.freester | last post by:
I have created to classes Matrix and System. System is made up of type matrix. ---------------------------------------------------------------------------------- class Matrix { private: int...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.