GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read
 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 23-Apr-2013, 01:39
swarna.bhatt swarna.bhatt is offline
New Member
 
Join Date: May 2012
Posts: 14
swarna.bhatt is an unknown quantity at this point

Assignment Operator overloading


Hello Everyone,

I have just started learning C++ . If my understanding is correct then Concept of operator overloading is used to make sure that we can so all mathematical operation with the objects , that we do with two variables (like , adding , subtraction , increment etc).

I am not able to understand the need for assignment operator .

Assignment operator copies of r-value to l-value

Like

CPP / C++ / C Code:
main()
{
int i = 10;
int j = 0;

//assignment 
j = i;

// now j = 10
}
similarly i tried doing the same with C++ object
CPP / C++ / C Code:
#include "stdafx.h"

#include <iostream>

using namespace std;

class Assign{
private:
	int m_Var;
	int m_Var2;
public:
	Assign()
	{
	}
	Assign(int var,int var2):m_Var(var),m_Var2(var2)
	{
	}
	void print()
	{
		cout<<m_Var<<endl<<m_Var2<<endl;
	}

};

void main()
{
	Assign obj1(9,10);
	Assign obj2;
	Assign obj3(100,90);

	obj1.print();
	
	obj2 = obj1=obj3;

	obj1.print();

	obj2.print();

	obj3.print();

}


in the above sample code , i have not done any assignment operator overload. But still i am getting proper out put
Code:
//obj1 before assignment 9 10 //obj1 after assignment 100 90 //obj2 after assignment 100 90 //obj3 100 90
After execution obj3 was copied to both obj1 and obj2 .

Can anybody please tell , why would i need to overload "=" while my purpose is served even without overlaoded "=".

Regards
Swarna.S
Last edited by admin : 23-Apr-2013 at 13:33. Reason: Please insert your example C/C++ codes between [CPP] and [/CPP] tags
  #2  
Old 23-Apr-2013, 06:22
Mexican Bob's Avatar
Mexican Bob Mexican Bob is offline
Regular Member
 
Join Date: Mar 2008
Location: Chicxulub, Yucatán
Posts: 686
Mexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the rough

Re: Assignment Operator overloading


Quote:
Originally Posted by swarna.bhatt
Hello Everyone,

I have just started learning C++ . If my understanding is correct then Concept of operator overloading is used to make sure that we can so all mathematical operation with the objects , that we do with two variables (like , adding , subtraction , increment etc).

I am not able to understand the need for assignment operator .

Assignment operator copies of r-value to l-value

Like
CPP / C++ / C Code:
main()
{
int i = 10;
int j = 0;

//assignment 
j = i;

// now j = 10
}
similarly i tried doing the same with C++ object
CPP / C++ / C Code:
#include "stdafx.h"

#include <iostream>

using namespace std;

class Assign{
private:
	int m_Var;
	int m_Var2;
public:
	Assign()
	{
	}
	Assign(int var,int var2):m_Var(var),m_Var2(var2)
	{
	}
	void print()
	{
		cout<<m_Var<<endl<<m_Var2<<endl;
	}

};

void main()
{
	Assign obj1(9,10);
	Assign obj2;
	Assign obj3(100,90);

	obj1.print();
	
	obj2 = obj1=obj3;

	obj1.print();

	obj2.print();

	obj3.print();

}


in the above sample code , i have not done any assignment operator overload. But still i am getting proper out put

//obj1 before assignment
9
10
//obj1 after assignment
100
90
//obj2 after assignment
100
90
//obj3
100
90

After execution obj3 was copied to both obj1 and obj2 .

Can anybody please tell , why would i need to overload "=" while my purpose is served even without overlaoded "=".

Regards
Swarna.S

Wow...that was ugly. Read: http://www.gidforums.com/t-5566.html

Not surprisingly, you need to use the keyword "operator" to overload an operator in C++.

Just because you "can" accomplish your goals without overloading operators, you may want to consider the appropriate implementation of operators.

CPP / C++ / C Code:
#include <iostream>

class Point {
public:
    Point() : m_x(0), m_y(0) {}
    Point(int x, int y) : m_x(x), m_y(y) {}
    Point(const Point& rhs) {
	m_x = rhs.m_x;
	m_y = rhs.m_y;
    }
    Point& operator=(const Point& rhs) {
	if (&rhs != this) {
	    m_x = rhs.m_x;
	    m_y = rhs.m_y;
	}
	return *this;
    }
    bool operator==(const Point& rhs) const {
	if ((rhs.m_x == m_x) && (rhs.m_x == m_y)) {
	    return true;
	}
	return false;
    }
    bool operator!=(const Point& rhs) const {
	if ((rhs.m_x != m_x) || (rhs.m_x != m_y)) {
	    return true;
	}
	return false;
    }
    friend std::ostream& operator<<(std::ostream& os, const Point& rhs) {
	os << rhs.m_x << "," << rhs.m_y;
	return os;
    }
    friend std::istream& operator>>(std::istream& is, Point& rhs) {
	is >> rhs.m_x;
	is.ignore(1, ',');
	is >> rhs.m_y;
	return is;
    }
    int x(void) const {
	return m_x;
    }
    int y(void) const {
	return m_y;
    }
    void x(int x) {
	m_x = x;
    }
    void y(int y) {
	m_y = y;
    }
private:
    int m_x;
    int m_y;
};

int main(void) {
    Point p1, p2, p3(1, 2);
    if (p1 == p2) {
	p2 = p3;
    }
    std::cout << p1 << " " << p2 << " " << p3 << std::endl;
    
    p3.x(3);
    p3.y(4);

    std::cout << p1 << " " << p2 << " " << p3 << std::endl;
    
    std::cout << "Enter a point (x,y) e.g. 100,200: ";
    std::cin >> p1;
    std::cout << p1 << " " << p2 << " " << p3 << std::endl;

    p2.x(88);
    p2.y(99);

    std::cout << p2.x() << "," << p2.y() << std::endl;
    
    return 0;
}


Output:

Code:
bash-3.2$ ./point 0,0 1,2 1,2 0,0 1,2 3,4 Enter a point (x,y) e.g. 100,200: 33,44 33,44 1,2 3,4 88,99

One should be able to see that by using operators effectively, we gain simplicity and a certain degree of elegance to our code that uses our object's interfaces. Some of the more challenging aspects such as what would an "increment or decrement operator" do to a point? Would it adjust the X or the Y or both? Since there is no meaningful way to increment or decrement a point, one shouldn't implement such operations. However, assignment and equality are useful operations. Therefore, not "all mathematical" operations make sense for a given object. However, we could easily implement operators for +, -, *, / if desired. Addition, subtraction and other mathematical operations on points seems like a plausible use and why not? Our class should know these things. Why not see if you can implement them yourself starting with the code I've provided? Use reasonable tests to ensure that they're working properly. We wouldn't want a division exception, right?

Note the polymorphic behavior of overloading of the x and y operations such that without arguments they are "getters" and with arguments they are "setters." Some would argue that this can be more confusing than "Set and Get" functions. My perspective is that it is relatively "clear enough" if you have some foundation in C++, but if not, then hopefully the (non-existent here) documentation will suffice.

Lastly (at least for now), I'd encourage you to think of better names for your classes. What is an Assign? It doesn't sound like a noun. It sounds more like a verb. Generally, a "class" should be a "noun" and represent something that we can think of as being something. Operations (aka methods or functions) can/should do something and should generally be thought of as verbs.

Eat, jump, sleep, run these things are "things" as much as they are things that things do...confused yet?


MxB
  #3  
Old 30-Apr-2013, 05:17
swarna.bhatt swarna.bhatt is offline
New Member
 
Join Date: May 2012
Posts: 14
swarna.bhatt is an unknown quantity at this point

Re: Assignment Operator overloading


Hi MxB
Thank you for the help.
Regards
  #4  
Old 17-Jul-2013, 16:27
steamerandy steamerandy is offline
New Member
 
Join Date: Aug 2012
Posts: 27
steamerandy will become famous soon enough

Re: Assignment Operator overloading


"Hello Everyone,

I have just started learning C++ . If my understanding is correct then Concept of operator overloading is used to make sure that we can do all mathematical operation with the objects , that we do with two variables (like , adding , subtraction , increment etc).

I am not able to understand the need for assignment operator ."

Sense you have just started learning C++. You probably needn't worry about operator overloading . The need for assignment operator overloading will be apparent when you are coding a class the needs to do it.

I think that to understand the reasoning of C++ class objects requires a historical view. There were many attempts to create a "do every thing language". IBMs PL1 for example. There have been others. The idea of being able to extend a programming language to include new data types as needed was a goal of many computer language developers.

LISP is a list processing language. LISP2 put the LISP list operations into a block structure language similar to ALGOL.

I wrote a LISP object that basically implements LISP2 in C++. The lists are dynamic objects. The assignment operator is over loaded so the use count of an object can be updated and tracked. LISP objects with a 0 use count are released. Releasing a list is a recursive operation that on a list release the use count of each object is decremented and if 0 releases it.

I wouldn't expect beginning programmers to grasp these more advanced concepts. When I worked at Cerritos Collage in the late 60's there was a student that came to me for help in writing an arithmetic expression evaluator. Basically a simple calculator program. Spent about a half hour explaining and coding a recursive decent parser evaluator in DEC-10 assembly. The recursion was beyond his level of understanding at that time. But he did figure it out and was quite proud when I visited him some 10 years later. He was teaching and the systems admin at the Cerritos. The challenge had inspired him to go on with his education.

Do not worry if you do not understand why one would need to overload any specific operator. The fact that you are asking the question indicates to me that you have the aptitude to understand it, if and when the need arises. I am sure that you will figure it out.

Andy
  #5  
Old 09-Nov-2016, 05:08
christylogu christylogu is offline
Account Disabled
 
Join Date: Nov 2016
Posts: 2
christylogu is on a distinguished road

Re: Assignment Operator overloading


overloading function for the assignment operator is not written in the class, the compiler generates the function to overload the assignment operator...
  #6  
Old 09-Nov-2016, 08:17
Mexican Bob's Avatar
Mexican Bob Mexican Bob is offline
Regular Member
 
Join Date: Mar 2008
Location: Chicxulub, Yucatán
Posts: 686
Mexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the rough

Re: Assignment Operator overloading


Quote:
Originally Posted by christylogu
overloading function for the assignment operator is not written in the class, the compiler generates the function to overload the assignment operator...
[/url]

This statement is technically inaccurate in a general sense of implementing a class definition. The key point is 'overloading' versus 'overriding', neither of which is the case here.

For a class that does not implement an assignment operator, the compiler will generate one. That is neither overloaded or overridden.

For a class that does implement an assignment operator, the compiler simply will not generate a 'default' assignment operator (which would be overridden, if it did generate a default assignment operator in spite of there being an explicit implementation).

My previous comments are perhaps more vague that necessary with respect to 'overloading' versus 'overriding.'

There should only ever be one implementation of a "copy assignment" operator. That should preclude any notion of "overloading" them.

Code:
class Foo { public: Foo& operator=(const Foo& rhs); // only "true" choice Foo& operator=(blah, blah, blah); // overloaded (should not be here!) }; class Bar : public Foo { public: Bar& operator=(const Bar& rhs); // overridden Foo? };

Revisit the terms overloaded versus overridden. In the future, I'll try to ensure that I am clearer on such details.


MxB
  #7  
Old 14-Jun-2017, 05:41
andrewetheridge andrewetheridge is offline
New Member
 
Join Date: Jun 2017
Location: Surfers Paradise, Queensland, Australia
Posts: 5
andrewetheridge can only hope to improve

Re: Assignment Operator overloading


I miss doing programming in C++
  #8  
Old 27-Jul-2017, 18:55
wq123 wq123 is offline
New Member
 
Join Date: Jul 2017
Posts: 2
wq123 is on a distinguished road

Re: Assignment Operator overloading


www.eyeglasses-outlet.com.co, pistons.nba-jersey.com, coach.euro-us.net, seahawks.nfljersey.us.com, www.chiflatirons.in.net, www.replica-handbags.com.co, www.cheap-jerseys.mex.com, www.nike-airmax.com.de, www.nike-store.com.de, colts.nfljersey.us.com, www.polos-ralphlauren.com.co, www.michaelkors-ins.com, www.nikeshoesoutlet.org.uk, suns.nba-jersey.com, www.ray-bans.co.uk, www.designer-handbagsoutlet.us.com, www.rolexwatchesforsale.us.com, www.raybans.org.es, www.nike-paschers.fr, www.jordan-retro.org, www.hollisteronlineshop.com.de, www.nikefree5.net, www.hermesoutlet.shop, www.christian-louboutins.co.uk, oakley.blackofriday.com, www.polos-outletstore.net, www.mbt-outlet.com, www.giuseppes-zanotti.com, www.oakleys-outlet.com.co, buccaneers.nfljersey.us.com, www.airhuaraches.co.uk, www.mcm-handbags.org, www.nikefactory.com.co, www.airmax-shoes.com, azcardinals.nfljersey.us.com, www.louboutinshoes.jp.net, www.nike-free-runs.de, www.oakleys-sunglasses.com.co, www.rolexwatches-canada.ca, www.chiflatiron.net.co, www.new-balanceshoes.es, www.barbour-jackets.us.com, www.pulseraspandora.com.es, www.michaelkors-canadaoutlet.ca, www.michael-kors.in.net, www.northfacejackets.fr, www.asicsoutlet.net, www.burberry-outletcanada.ca, www.juicycoutureoutlet.net.co, www.nfljersey.us.com, www.coachsoutletonline.in.net, www.converses-outlet.com, www.ray-bansoutlet.org.uk, trailblazers.nba-jersey.com, www.nike-roshe-run.de, knicks.nba-jersey.com, packers.nfljersey.us.com, www.coach-factoryoutlet.net.co, www.puma-shoesoutlet.com, www.levisjeans.com.co, rockets.nba-jersey.com, www.polo-ralphlaurens.us.com, celine.blackofriday.com, www.timberlandspaschere.fr, www.giuseppezanotti.com.co, www.vansschuhe.com.de, www.pradahandbags.net.co, www.oakleys.mex.com, texans.nfljersey.us.com, heat.nba-jersey.com, www.longchampoutlet.com.co, www.true-religions.com, www.rayban-sunglasses.co, www.pradas.com.de, www.poloralphlaurenoutlet.net.co, www.cheap-baseballbats.us, www.rayban-sunglasses.fr, www.cheapjerseys.net.co, www.ralphlaurenonlineshop.de, www.hollisters.us.com, www.burberryonlineshop.de, www.iphonecases.net.co, www.armani-exchange.in.net, www.raybans-cher.fr, www.oakley-sbocco.it, www.nikefree-run.net, hornets.nba-jersey.com, www.pandora-jewelry.com.de, www.scarpe-hoganshoes.it, www.thomas-sabos.com.de, www.hollister.com.se, www.timberland-boots.com.co, www.long-champ.com.de, www.uhren-stores.de, ralphlauren.blackofriday.com, www.newoutletonlinemall.com, coach-outlet.tumblr.com, www.nike-airmax.us.com, www.versace-outlet.com, www.michaelkors.mex.com, chargers.nfljersey.us.com, www.puma-shoes.de, www.swarovski-australia.com.au, longchamp.blackofriday.com, www.michael-korsoutlet.co.uk, 49ers.nfljersey.us.com, www.oakleys-frame.com.co, www.ray-bansoutlet.com.co, www.nike-skors.com.se, www.burberrys-bags.com, www.nike-mercurial.com, www.beats-by-dre.com.co, www.babyliss-pros.com, www.burberrysoutletstore.com, www.reeboks.com.de, jazz.nba-jersey.com, www.michaelkors.co.nl, www.marcjacobs-outlet.com, www.converseschuhe.com.de, www.hoodies-store.com, www.montblancoutlet.com.co, www.coach-outlets.net.co, www.ok-em.com, bengals.nfljersey.us.com, lakers.nba-jersey.com, www.wedding-dresses.cc, www.cheapnhljerseys.us.com, www.cheapoakleys.com.co, www.juicycouture.com.co, www.burberrys-handbags.com, www.the-northfaces.net.co, www.the-northfacejackets.net.co, www.michael-korsoutletonline.com.co, www.mcmhandbags.com.co, www.tommyhilfigerca.ca, www.cheap-michaelkors.com.co, www.outletburberrybags.com, falcons.nfljersey.us.com, www.coachoutlet-online.com.co, www.zcoachoutlet.com, www.swarovski-canada.ca, www.jordanshoes.net.co, www.barbour-jackets.com, www.bottega-bags.com, www.adidas-shoes.in.net, www.long-champoutlet.com, www.bcbg-dresses.net, www.bcbg-maxazria.ca, www.hugo-boss.com.co, www.michael-kors.cc, www.truereligions.net, www.ferragamos.us.com, www.timberlandbootsoutlet.us.com, www.nikestoreoutlet.us, www.nike-schoenen.co.nl, www.mcmbackpacks.com.co, www.nba-shoes.com, www.valentino-shoesoutlet.us.com, www.michaelskors-outlet.co.uk, www.thenorth-face.com.co, patriots.nfljersey.us.com, clippers.nba-jersey.com, www.burberrys-outlet.in.net, raiders.nfljersey.us.com, www.coachfactory.shop, www.ralphlaurens-outlet.co.uk, www.air-yeezys.com, www.ed-hardy.us.com, www.timberlandshoes.net.co, www.new-balance-schuhe.de, www.oakley-sunglasses2017.net, www.clothes-outletstore.com, www.ralphslaurenoutlet.us.com, www.roshe-runs.co.uk, michaelkors.euro-us.net, www.raybans-sunglasses.net.co, www.nike-rosherun.com.es, www.oakleysunglasses-canada.ca, www.fendi-outlet.in.net, www.christianlouboutinoutlet.net.co, www.nikeshoes-outlet.com, www.katespades.com.co, www.givenchy.com.co, www.burberry-store.com, www.nike-air-force.de, www.christian-louboutinshoes.in.net, www.the-northface.ca, www.nike-shoesoutlet.com, www.jerseys-store.com, www.calvin-kleins.in.net, www.katespadeoutlet.gb.net, www.pandorajewelry.top, www.ferragamo.net.co, timberwolves.nba-jersey.com, thunder.nba-jersey.com, www.hollister-clothingsstore.com, www.basketballshoes.com.co, cavaliers.nba-jersey.com, www.woolrich-clearance.com, www.vibram-fivefingers.in.net, www.tracksuits.com.co, www.ralph-laurenoutletonline.com, www.raybans-outlet.cc, bulls.nba-jersey.com, www.cheapthomas-sabos.org.uk, www.air-jordanshoes.us, www.nikefree-runs.org.uk, www.nike-shoes.com.co, www.hollisters-canada.ca, www.oakley-sunglass.net.co, www.hoganshoes.org.uk, www.true-religion.com.co, www.beatsbydre.com.co, www.ralphs-laurenpolo.co.uk, kings.nba-jersey.com, pacers.nba-jersey.com, www.hermes-birkinoutlet.net, www.prada-outlet.com.co, www.omega-watches.com.co, www.truereligion-outlet.us.org, www.tnf-jackets.us, 76ers.nba-jersey.com, www.adidas-schuheonline.de, www.under-armouroutlet.com, www.prada-shoes.com.co, titans.nfljersey.us.com, www.cheap-rayban.com.co, www.tommy-hilfigers.com.co, www.ray-bans.net.co, warriors.nba-jersey.com, www.kates-spade.com, www.north-face.com.co, www.adidas-shoes.es, www.adidasshoes.com.se, magic.nba-jersey.com, www.michael-korsbags.com.co, www.michaelkors-outletonline.cc, www.burberry-bagsoutlet.co.uk, www.raybansbocco.it, www.coachfactory.cc, www.salvatoreferragamo.us.com, www.nikeairmax.com.de, www.burberry-outlets.org.uk, www.airmax.com.se,
  #9  
Old 02-Aug-2017, 02:46
pravin007techno pravin007techno is offline
New Member
 
Join Date: Sep 2014
Posts: 11
pravin007techno is an unknown quantity at this point

Re: Assignment Operator overloading


Thaks For your Information Regarding Assignment Operator overloading.
 


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Help with an assignment: Simulating CPU scheduling. neojb1989 C++ Forum 7 27-Mar-2017 17:09
Need Help Completing this Grade Calculator Assignment chem C Programming Language 5 23-Jul-2013 12:07
Help with an inheritance assignment please? cppjosh C++ Forum 4 04-May-2011 17:31
Circular Linked Queue Copy Constructor and Assignment Operator Not Working? wc3promet C++ Forum 1 06-Oct-2008 03:00
help with c++ object assignment Mjkramer21 C++ Forum 31 14-Apr-2004 18:51

Network Sites: GIDNetwork · GIDApp · GIDBlog · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 23:12.


vBulletin, Copyright © 2000 - 2017, Jelsoft Enterprises Ltd.