473,811 Members | 3,220 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Confusion overloading '=' operator

9 New Member
I'm trying to implement a = operater to set one circle or rectangle to another and this is giving me all kind of bugs.


Expand|Select|Wrap|Line Numbers
  1. #include <iostream.h>
  2.  
  3.  
  4. class Shape
  5. {
  6.   private:
  7.      int x_Center, y_Center;
  8.  
  9.   public:
  10.     Shape()
  11.     {
  12.     cout <<"In defualt constructer";
  13.     }
  14.     Shape(Shape& sh)
  15.     {
  16.     x_Center=sh.x_Center;
  17.     y_Center=sh.y_Center;
  18.     }
  19.      // Constructors
  20.      Shape(int cx, int cy)
  21.     {
  22.         x_Center=cx;
  23.         y_Center=cy;
  24.     }
  25.  
  26.      // Member functions
  27.      int getCenter_X();
  28.      int getCenter_Y();
  29.      virtual void draw()=0;
  30. };
  31.  
  32. class Rectangle : public Shape
  33. {
  34. private:
  35.     int length,width;
  36.  
  37.  public:
  38.  
  39.   // Default constructor
  40.   Rectangle (Rectangle& r) : Shape(r)
  41.     {
  42.     length=r.length;
  43.     width=r.width;
  44.     }
  45.  
  46.   // Constructor
  47.   Rectangle (int cx, int cy,int l,int w) : Shape(cx, cy)
  48.     {
  49.     length=l;
  50.     width=w;
  51.       cout << "In Rectangle constructor" << endl;
  52.     }
  53.  
  54.  
  55.  
  56.     // Destructor
  57.     ~Rectangle ()
  58.       {
  59.     cout << "In Rectangle destructor" << endl;
  60.       }
  61.  
  62.     void draw()
  63.     {
  64.     cout <<"In drawing of Rectangle"<<endl;
  65.     }
  66.  
  67.     Rectangle & operator=(const Rectangle &obj)
  68.     {
  69.             return Rectangle(obj.getCenter_X(),obj.getCenter_Y(),obj.length,obj.width);
  70.     }
  71.     // Methodds
  72.     void printAllValues();
  73. };
  74.  
  75. class Circle : public Shape
  76. {
  77. private:
  78. int diameter;
  79.  
  80.  public:
  81.  
  82.   // Default Constructor
  83.   Circle ()
  84.     {
  85.       cout << "In the default constructor of Circle" << endl;
  86.     }
  87.  
  88.     Circle (Circle& r) : Shape(r)
  89.     {
  90.     diameter=r.diameter;
  91.     }
  92.   // Constructor
  93.   Circle (int cx, int cy, int dia) : Shape (cx, cy)
  94.     {
  95.       cout << "In Circle Constructer" << endl;
  96.       diameter=dia;
  97.     }
  98.  
  99.     // Destructor
  100.     ~Circle ()
  101.       {
  102.     cout << "In Circle destructor" << end}
  103.       }
  104.       void draw()
  105.     {
  106.     cout <<"In drawing of Circle"<<endl;
  107.     }
  108.     Circle & operator=(const Circle &obj)
  109.     {
  110.         return Circle(getCenter_X(),getCenter_Y(),diameter);
  111.     }
  112.     // Methods
  113.     void printAllValues();
  114. };

Could someone please help point me in the right diretion please.
Oct 21 '07 #1
4 1363
weaknessforcats
9,208 Recognized Expert Moderator Expert
Let's look at the situation:

You have a Shape.

Therefor you need a Shape assignment operator.

You have Circle deriving from Shape.

Therefore you need a Circle assignment operator.

In each case the assignment operator must change the this object since iot is that object that in to the left of the operator (and thereby, the hidden firstargument of the assignment operator function).

For Shape:
1) assign the values of the argument to the this object.
2) do not assign the this obect ot itself.

Expand|Select|Wrap|Line Numbers
  1. Shape Shape::operator=(const Shape& rhs)
  2. {
  3.    if (this == rhs) return *this;    //nothing to do if self-assignment
  4.    this->x_Center = rhs.x_Center;
  5.    this->y_Center = rhs.y_Center;
  6.    return *this;
  7. }
  8.  
For Circle:
1) assign the base class object first
2 assign the values of the argument to the this object.
3) do not assign the this obect ot itself.
Expand|Select|Wrap|Line Numbers
  1. Circle Circle::operator=(const Circle& rhs)
  2. {
  3.    if (this == rhs) return *this;    //nothing to do if self-assignment
  4.    Shape::operator=(*this);       //assign the base class object
  5.    this->diameter= rhs.diameter;
  6.    return *this;
  7. }
  8.  

That said, it does not look like your Circle IS-A kind of Shape since it does not use x_Center or y_Center at all. I question whether your class inheritance model is correct.
Oct 21 '07 #2
hjast
9 New Member
Thanks a lot, but shouldn't I create a new object in the heap and then copy all attribtes and then give the pointer to that? Does the code you just exampled make a copy operater?

I am a little confused on why you return itself. Please clarify.

Reuben
Oct 21 '07 #3
gpraghuram
1,275 Recognized Expert Top Contributor
Thanks a lot, but shouldn't I create a new object in the heap and then copy all attribtes and then give the pointer to that? Does the code you just exampled make a copy operater?

I am a little confused on why you return itself. Please clarify.

Reuben

You need not create a new object and retun it.
Becos the function is called by a object and the values you change for this affects the object calling it.

Raghuram
Oct 22 '07 #4
weaknessforcats
9,208 Recognized Expert Moderator Expert
Thanks a lot, but shouldn't I create a new object in the heap and then copy all attribtes and then give the pointer to that? Does the code you just exampled make a copy operater?

I am a little confused on why you return itself. Please clarify.

Reuben
The fact that your assignment operator returns a Circle means that a copy is returned. That means you should have a copy constructor to make that copy.

If you create your own copy on the heap and try to return it, you still need a copy constructor to make the copy top be returned. Plus now you have to delete the copy you made before returning.

It's not my code that requires a copy. It's the fact that the function returns a Circle.

By returning *this, I am calling Circle::Circle( const Circle& rhs), which os your copy copnstructor.

If you don't have one, the compiler trots out its default copy constructor which makes memberwise copies of each of your data members. If all of your data members a built-in types, like int, then this default will work fine.
Oct 22 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

7
1386
by: raj | last post by:
I need explanation of the behavior of the following code. When run as it is, it gives error. //-------------------------<start>------------------ #include <iostream.h> #include <stdlib.h> class ABC { private: int x;
5
5252
by: | last post by:
Hi all, I've been using C++ for quite a while now and I've come to the point where I need to overload new and delete inorder to track memory and probably some profiling stuff too. I know that discussions of new and delete is a pretty damn involved process but I'll try to stick to the main information I'm looking for currently. I've searched around for about the last too weeks and have read up on new and overloading it to some extent but...
3
1600
by: Zork | last post by:
Hi, I am a little confused with const functions, for instance (here i am just overloading the unary+ operator) if i define: 1) Length Length :: operator+ ( void ) const {return * this;} ... I get no error... 2) Length & Length :: operator+ ( void ) const {return * this;} ... I get the error -> 'return' : cannot convert from 'const class Length' to
4
2625
by: Chris Mabee | last post by:
Hello all, and Merry Christmas, I'm having a problem understanding an example of an array based implementation of a stack in a textbook of mine. The code in question is written below. The syntax is directly as in the book, except for where I added the comments at the lines I wanted to refer to or to skip sections of code. template <class Element_Type> class Stack {
7
2553
by: Kelly Mandrake | last post by:
I've implemented a class with operator+ overloaded and I also provided my own copy constructor; The problem is my copy constructor is being called twise and I dont understand why. I believe the copy constructor is being called when I add the two class objects. But if this is so, then why because I have overloaded the + operator should I not get the result from that and not from copy constructor? I have the following: int main(int...
5
2492
by: luca regini | last post by:
I have this code class M { ..... T operator()( size_t x, size_t y ) const { ... Operator overloading A ....} T& operator()( size_t x, size_t y )
2
2265
by: brzozo2 | last post by:
Hello, this program might look abit long, but it's pretty simple and easy to follow. What it does is read from a file, outputs the contents to screen, and then writes them to a different file. It uses map<and heavy overloading. The problem is, the output file differs from input, and for the love of me I can't figure out why ;p #include <iostream> #include <fstream> #include <sstream>
3
3286
by: y-man | last post by:
Hi, I am trying to get an overloaded operator to work inside the class it works on. The situation is something like this: main.cc: #include "object.hh" #include "somefile.hh" object obj, obj2 ;
2
4446
by: Colonel | last post by:
It seems that the problems have something to do with the overloading of istream operator ">>", but I just can't find the exact problem. // the declaration friend std::istream & operator>(std::istream & in, const Complex & a); // the methods correspond to the friend std::istream & operator>(std::istream & in, const Complex & a) { std::cout << "real: ";
8
2979
by: Wayne Shu | last post by:
Hi everyone, I am reading B.S. 's TC++PL (special edition). When I read chapter 11 Operator Overloading, I have two questions. 1. In subsection 11.2.2 paragraph 1, B.S. wrote "In particular, operator =, operator, operator(), and operator-must be nonstatic member function; this ensures that their first operands will be lvalues". I know that these operators must be nonstatic member functions, but why this ensure their first operands will...
0
9730
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9605
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
10651
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
10392
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...
1
10403
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9208
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...
1
7671
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5693
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3020
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.