Help adding objects

B

Brian Dumas

I would like to do something like the following

class TMyClass
{
......
}

TMyClass* mc1 = new TMyClass;
TMyClass* mc2 = new TMyClass;
TMyClass* mc3=mc1+mc2;

Where the addition mc1+mc2 would take the desired information from each
object, put them together , then store them mc3. I tried overloading the
operator+, but when I compile the mc3=mc1+mc2 line, the compiler complains
about invalid pointer addition.

Anyone have an ideas?

Thanks for any and all help. It is greatly appreciated.
Brian Dumas
 
R

Ravi

Brian said:
I would like to do something like the following

class TMyClass
{
.....
}

TMyClass* mc1 = new TMyClass;
TMyClass* mc2 = new TMyClass;
TMyClass* mc3=mc1+mc2;

mc1 and mc2 are pointers and it makes no sense to add two pointers ever.

You could try

TMyClass* mc3 = new TMyClass(*mc1+*mc2);

where you overload the + operator suitably and define a copy constructor
if needed.
 
T

Thomas Matthews

Brian said:
I would like to do something like the following

class TMyClass
{
.....
}

TMyClass* mc1 = new TMyClass;
TMyClass* mc2 = new TMyClass;
TMyClass* mc3=mc1+mc2;

Where the addition mc1+mc2 would take the desired information from each
object, put them together , then store them mc3. I tried overloading the
operator+, but when I compile the mc3=mc1+mc2 line, the compiler complains
about invalid pointer addition.

Anyone have an ideas?

Thanks for any and all help. It is greatly appreciated.
Brian Dumas

In your example above, all the variables are pointers to
the classes, not instances of the classes. The compiler
is correct, because you are telling it to add pointers
together.

I think you meant:
TMyClass * mc3 = new TMyClass; // create an instance for the result.
*mc3 = *mc1 + *mc2; // Add the instances, not the pointers.

BTW, there is no requirement for classes to start with a 'T'
or a 'C'. Feel free to be different.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
 
D

David Harmon

operator+, but when I compile the mc3=mc1+mc2 line, the compiler complains
about invalid pointer addition.

Right. Stop using pointers. Stop using "new".
Put down that Java book and step away from it.
 

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

Forum statistics

Threads
474,161
Messages
2,570,891
Members
47,423
Latest member
henerygril

Latest Threads

Top