By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,804 Members | 1,634 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,804 IT Pros & Developers. It's quick & easy.

operator + without =

P: n/a
Hi,

Can I define a class that has an operator+ set:

A operator+(A a, double d);
A operator+(double d, A a);
....

without defining an = operator for the class? Just different
constructors?

class A
{
A() {dat=new int[1]; *dat=0;}
A(double d) {dat=new int[1]; *dat=(int)d;}
};

--
-Gernot
int main(int argc, char** argv) {printf
("%silto%c%cf%cgl%ssic%ccom%c", "ma", 58, 'g', 64, "ba", 46, 10);}

________________________________________
Looking for a good game? Do it yourself!
GLBasic - you can do
www.GLBasic.com
Jul 22 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a

"Gernot Frisch" <Me@Privacy.net> wrote in message
news:2n***********@uni-berlin.de...
Hi,

Can I define a class that has an operator+ set:

A operator+(A a, double d);
A operator+(double d, A a);
...

without defining an = operator for the class? Just different
constructors?

class A
{
A() {dat=new int[1]; *dat=0;}
A(double d) {dat=new int[1]; *dat=(int)d;}
};


I don't see why not (at least from a language POV). Are you having any
specific difficulty?

john
Jul 22 '05 #2

P: n/a
Gernot Frisch wrote:
Can I define a class that has an operator+ set:

A operator+(A a, double d);
A operator+(double d, A a);
...

without defining an = operator for the class? Just different
constructors?

class A
{
A() {dat=new int[1]; *dat=0;}
A(double d) {dat=new int[1]; *dat=(int)d;}
};


"You have the right to define the operator=. If you give up your right,
the operator= will be defined for you" :-)

My comment here is: if you don't define the operator= _and_ your class
has some dynamic memory management in it, you are looking at a very
unpleasant result when you want to write

A pi(3.14159);
A e(2.7182818);
A d;

d = pi + e;

The 'dat' member will either be destroyed twice or you will have a memory
leak (depends on whether you have the d-tor defined correctly).

See "The Rule of Three".

Victor
Jul 22 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.