operator + without =

G

Gernot Frisch

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
 
J

John Harrison

Gernot Frisch said:
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
 
V

Victor Bazarov

Gernot said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,812
Latest member
GracielaWa

Latest Threads

Top