473,785 Members | 2,916 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

question on operator overloading.

Hello Group,

Please take a look at the following (simple) C++ code (at the end of
this post) that does operator overloading. It gives me the following
compile error:

complex.cpp: In function `int main()':
complex.cpp:59: no match for `cmplx& = cmplx' operator
complex.cpp:26: candidates are: cmplx& cmplx::operator =(cmplx&)

I am guessing that the error has something to do with the way I have
defined operator=. But I am not sure what went wrong. I am passing all
arguments as references because in my actual code the objects that I am
dealing with a large and it would be inefficient to pass them as copies
to operator=(). I am guessing the C++ interprets the line,

c = a + b;

as

c.operator=(ope rator+(a, b));

which should work based on the definitions in the code listed below:

class cmplx
{
double real, imag;

public :
cmplx()
{
;
}
cmplx(double realP, double imagP)
{
real = realP;
imag = imagP;
}

cmplx(cmplx &another)
{
real = another.real;
imag = another.imag;
}

cmplx &operator=(cmpl x &another)
{
real = another.real;
imag = another.imag;
return *this;
}

cmplx& operator+=(cmpl x &another)
{
real += another.real;
imag += another.imag;
return *this;
}

void print(void)
{
printf("[%d + j %d]", real, imag);
}
};

cmplx operator+(cmplx &first, cmplx &second)
{
cmplx tmp(first);
tmp += second;
return tmp;
}

int main(void)
{
cmplx *a, b, c;

a = new cmplx(1, 1);
b = *a;

c = b + *a;

printf("a = "); a->print(); printf("\n");
printf("b = "); b.print(); printf("\n");
printf("c = "); c.print(); printf("\n");
delete a;
}

Thanks a lot !
-Vijay.

Jul 22 '05 #1
6 1379
* Master of C++:

Hm.

class cmplx
STYLE. Don't use silly abrvatns.

{
double real, imag;
STYLE. Use systematic indentation.

public :
cmplx()
{
;
STYLE. Don't use superflous semicolons.
STYLE. Use systematic indentation.

}
STYLE. Do use blank lines between functions.

cmplx(double realP, double imagP)
{
real = realP;
STYLE. Use systematic indentation.
imag = imagP;
}
STYLE. Use initializer lists.
STYLE. Use systematic indentation.

cmplx(cmplx &another)
DESIGN ERROR. Use const argument.
{
real = another.real;
imag = another.imag;
}
STYLE. Use initializer lists.
STYLE. Use systematic indentation.


cmplx &operator=(cmpl x &another)
DESIGN ERROR. Use const argument.
{
real = another.real;
STYLE. Use systematic indentation.
imag = another.imag;
return *this;
}
STYLE. Use systematic indentation.

cmplx& operator+=(cmpl x &another)
DESIGN ERROR. Use const argument.
{
real += another.real;
STYLE. Use systematic indentation.
imag += another.imag;
return *this;
}

void print(void)
DESIGN ERROR. Don't do i/o in a data handling class.
STYLE. Don't use 'void' argument list (C-ism).

{
printf("[%d + j %d]", real, imag);
STYLE. As a newbie, do not use C library i/o, use typesafe C++ i/o.
ERROR. Because you failed to do that you have an error here.
STYLE. Use systematic indentation.
}
};
STYLE. Use systematic indentation.


cmplx operator+(cmplx &first, cmplx &second)

DESIGN ERROR. Use const argument.
{
cmplx tmp(first);

STYLE. Use systematic indentation.
tmp += second;
return tmp;
}

int main(void)
STYLE. Don't use 'void' argument list (C-ism).
{
cmplx *a, b, c;
STYLE. Use systematic indentation.
STYLE. As a newbie, don't use raw pointers. Use e.g. std::auto_ptr.

a = new cmplx(1, 1);

b = *a;

c = b + *a;

printf("a = "); a->print(); printf("\n");
STYLE. As a newbie, do not use C library i/o, use typesafe C++ i/o.

printf("b = "); b.print(); printf("\n");
printf("c = "); c.print(); printf("\n");
delete a;
}


--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #2
Hello Mr. Steinbach,

Thanks for your suggestions. I normally use most of the design and
style guidelines that you have suggested (Google Groups removed all the
indentation I used when I copied and pasted the code - and pressed the
post button). I wrote this piece of code in a bit of a hurry to
illustrate my problem - and it does gives the same compile error.

I removed the operator=() function from my original listing and the
code compiled properly. I am not able to explain why this happens
though. What else is wrong with my implementation of the operator=()
function ? (other than style errors and fact that I forgot to include
'const' before the arguments).

Thanks,
Vijay.

BTW, please ignore my nickname ("Master of C++" - somehow crossed my
mind when I subscribed to this group). I am neither a newbie, nor an
expert - but somewhere in the middle...

Jul 22 '05 #3
Master of C++ wrote:
Hello Mr. Steinbach,

Thanks for your suggestions. I normally use most of the design and
style guidelines that you have suggested (Google Groups removed all the
indentation I used when I copied and pasted the code - and pressed the
post button). I wrote this piece of code in a bit of a hurry to
illustrate my problem - and it does gives the same compile error.

I removed the operator=() function from my original listing and the
code compiled properly. I am not able to explain why this happens
though. What else is wrong with my implementation of the operator=()
function ? (other than style errors and fact that I forgot to include
'const' before the arguments).
Show us your new code.

The "const" is significant.

These are seen as two separate functions.
void f( const int & );
void f( int & );
The compiler auto generates a copy constructor, yet you
provided one:

cmplx(cmplx &another)
{
real = another.real;
imag = another.imag;
}
cmplx.cpp:63: error: no match for 'operator=' in 'c = operator+(cmplx &,
cmplx&)(((cmplx &)a))'
cmplx.cpp:29: note: candidates are: cmplx& cmplx::operator =(cmplx&)

It seems like the compiler didn't like to pass a temporary as a
non-const to the '=' operator.

Adding "const" to operator= then gets this error message:

cmplx.cpp:63: error: no matching function for call to `cmplx::cmplx(c mplx)'
cmplx.cpp:21: note: candidates are: cmplx::cmplx(cm plx&)

Now we're missing the constructor that takes a const - fix that and it
will compile.

Anyhow - when you're done, it would look somthing like this:

#include <iostream>

class cmplx
{
double m_real, m_imag;

public :

cmplx()
{
}

cmplx(double realP, double imagP)
: m_real( realP ),
m_imag( imagP )
{
}

cmplx(const cmplx &another)
: m_real( another.m_real ),
m_imag( another.m_imag )
{
}

cmplx & operator=(const cmplx &another)
{
m_real = another.m_real;
m_imag = another.m_imag;
return *this;
}
cmplx & operator+=(cmpl x &another)
{
m_real += another.m_real;
m_imag += another.m_imag;
return *this;
}

double real() const
{
return m_real;
}

double imag() const
{
return m_imag;
}
};

const cmplx operator+( const cmplx &first, const cmplx &second )
{
return cmplx(
first.real() + second.real(),
first.imag() + second.imag()
);
}

namespace std {

template<
typename w_char_type,
class w_traits

basic_ostream<w _char_type, w_traits>& operator << (
basic_ostream<w _char_type, w_traits> & o_ostream,
const cmplx & value
) {

o_ostream << "[" << value.real() << " + j " << value.imag() << "]";
return o_ostream;
}

} // namespace std

int main(void)
{
cmplx *a, b, c;

a = new cmplx(1, 1);
b = *a;

c = b + *a;

std::cout << "a = " << * a << "\n";
std::cout << "b = " << b << "\n";
std::cout << "c = " << c << "\n";

delete a;
}
Jul 22 '05 #4
Dear Mr. Mariani,

Thanks for the suggestion ! Adding the 'const' keyword did work. But I
am surprised. I thought that the 'const' keyword is just a matter of
style if I am 100% sure that I will not be modifying the object that is
referenced using the pointer that is sent as an argument. It appears
that there is more significance to the keyword than I thought it had.
Thanks for pointing this to me.

Here is the modified code in which I commented out the operator=() part
and retained the copy constructor (I hope this time Google Groups does
not remove the indents when I post this message). I have another
question though. How does the compiler auto-generate a copy constructor
? (This class was simple, what about a more complex class that requires
complicated copy operations).

Thanks,
-Vijay.

class cmplx
{
double real, imag;

public :
cmplx()
{
;
}
cmplx(double realP, double imagP)
{
real = realP;
imag = imagP;
}

cmplx(cmplx &another)
{
real = another.real;
imag = another.imag;
}

/*
cmplx& operator=(const cmplx &another)
{
real = another.real;
imag = another.imag;
return *this;
}
*/

cmplx& operator+=(cmpl x &another)
{
real += another.real;
imag += another.imag;
return *this;
}

void print(void)
{
printf("[%.2f + j %.2f]", real, imag);
}
};

cmplx operator+(cmplx &first, cmplx &second)
{
cmplx tmp(first);
tmp += second;
return tmp;
}

int main(void)
{
cmplx a(1, 1), b(2, 2), c;
c = b + a;

printf("a = "); a.print(); printf("\n");
printf("b = "); b.print(); printf("\n");
printf("c = "); c.print(); printf("\n");
}

Jul 22 '05 #5

"Master of C++" <ma************ *@gmail.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
Dear Mr. Mariani,

Thanks for the suggestion ! Adding the 'const' keyword did work. But I
am surprised. I thought that the 'const' keyword is just a matter of
style if I am 100% sure that I will not be modifying the object that is
referenced using the pointer that is sent as an argument.
No ... const-ness is an integral and extremely important concept in C++ that
should be considered even at the earliest stages of design. I think it is
reasonable to say that code that is not const-correct is not correct at all.
It appears that there is more significance to the keyword than I
thought it had. Thanks for pointing this to me.


You should really look deeper into this ... pick up a copy of a good C++
book for more detailed examples .. I suggest Herb Sutter's "Exceptiona l
C++", or Scott Meyer's "Effective C++". Actually, a nice worked example of
const-correctness is on Herb Sutter's website at:
http://www.gotw.ca/gotw/006.htm

HTH,

Dave Moore
Jul 22 '05 #6
Master of C++ wrote:
Dear Mr. Mariani, ....

I have another question though. How does the compiler auto-generate a copy constructor
? (This class was simple, what about a more complex class that requires
complicated copy operations).


The compiler will generate a "default" copy constructor and assignment
that basically does a member-wise copy (or assignment) of all the elements.

If you need to do somthing else, you had better provide one. You
probably need to read-up on the "rule of three".

"Any class that has an explicitly defined destructor, copy constructor
or assignment operator generally needs all three."
Jul 22 '05 #7

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

Similar topics

7
3694
by: Jessica | last post by:
Hi, I have a design question. I am making a time series analysis tool. Since I already use STL vector to represent time series, is there a need to implement a class for the time series object? Right now I just use typedef vector<double>TS; Is that enough? I feel that I am not taking advantage of the C++
11
1751
by: billnospam | last post by:
Is it possible to overload operators in vb.net? Is it possible to do programmer defined boxing on byvalue variables in vb.net?
16
2620
by: Edward Diener | last post by:
Is there a way to override the default processing of the assignment operator for one's own __value types ? I realize I can program my own Assign method, and provide that for end-users of my class, but I would like to use internally my own = operator for some of my value types, so I can say "x = y;" rather than "x.Assign(y);". The op_Assign operator seems impossibly broken since it takes __value copies of the two objects. Perhaps there is...
16
3097
by: gorda | last post by:
Hello, I am playing around with operator overloading and inheritence, specifically overloading the + operator in the base class and its derived class. The structure is simple: the base class has two int memebers "dataA", "dataB". The derived class has an additional int member "dataC". I am simply trying to overload the + operator so that 'adding' two objects will sum up the corresponding int members.
7
1832
by: Eckhard Lehmann | last post by:
Hi, I try to recall some C++ currently. Therefore I read the "Standard C++ Bible" by C. Walnum, A. Stevens and - of course there are chapters about operator overloading. Now I have a class xydata with operator- overloaded: class xydata { public:
110
4529
by: Vijay Kumar R Zanvar | last post by:
Hi, Which section of C99 says that return value of malloc(3) should not be casted? Thanks. -- Vijay Kumar R Zanvar My Home Page - http://www.geocities.com/vijoeyz/
3
2301
by: karthik | last post by:
The * operator behaves in 2 different ways. It is used as the value at address operator as well as the multiplication operator. Does this mean * is overloaded in c?
3
3283
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 ;
8
2976
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...
5
1338
by: Joseph Y. Oh | last post by:
Hello, class A { public: A& operator+=( const A& a ) = 0; }; class B1:public A { public: A& operator+=( const A& a ) { ... }
0
9645
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
10330
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...
1
10093
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
9952
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8976
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
6740
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4053
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2880
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.