473,778 Members | 1,886 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2282
On Aug 22, 3:56 pm, sam_...@yahoo.c o.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
"constructo r". 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************ *********@q3g20 00prf.googlegro ups.com>,
Neelesh Bodas <ne***********@ gmail.comwrites
>On Aug 22, 3:56 pm, sam_...@yahoo.c o.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.c o.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=(MyTyp e 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...@gmai l.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=(MyTyp e 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.(pointero ids , 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_st ring& s):str(new char[s.sz]),sz(s.sz)
{memcpy(str,s.s tr,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==(cons t my_string& right){
if(sz!=right.sz ) return false;
return 0==memcmp(str,r ight.str,sz);
};

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

~my_string(){de lete[] 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,allo cation/
deallocation(ne w/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
17879
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. Why can't the = (assignment) operator be overloaded as a friend function ? I work in VS 6.0 ( Win2000 ) as when i referred the MSDN documen'n it said the following :
5
6887
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: // TestA.h --------------------------------------- #include <iostream> enum Aval { FIRST_VALUE,
9
462
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 ensure that a client of the program cannot assign an object of the class to itself. The if() condition would be placed within the function definition to compare the operand in the function parameter is not the same as the temporary object being...
4
1826
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 memory problem that I'm not readily seeing that lies within the overloaded operator - I think pertaining to the temporary class object that is created and used to return a value of the operands and the pointer variable of the class. Could someone...
1
2225
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 pertaining to casting class A to class B, the implementation of the
2
1690
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 as you can see in the constructor. Class Matris should create a matris by using class Intvektor. So what I want to have is a pointer to an array of Intvektor and in each positionindex in this array will I have a pointer to an array of Intvektor
5
2293
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 my C++.NET 2.0 textbook does not have one. I tried to build one using the format as taught in my regular C++ book, but I keep getting compiler errors. Some errors claim (contrary to my book) that you cannot use a static function, that you must...
9
2059
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 the + operator by means of a friend function. Everything worked fine until I decided to use a variable array size (by using new/delete), now I get an error when a temporary object is deleted (e.g. after addition), the error occurs at the delete...
3
3921
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 row, col; double *data public: Matrix(const int& M, const int& N): row(M), col(N)
0
9464
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10292
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10122
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8954
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6722
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5368
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5497
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3627
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2860
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.