donald
donald

Reputation: 489

Calling an overloaded operator from a pointer

I have a simple C++ test class, that has a char * operator() working fine. The thing is, when I'm creating it on the heap, I can't use it.

test t;
printf(t);

is ok, but

test *t=new test();
printf(t);

isn't. Is there any way around it beside printf(*t)?

Upvotes: 2

Views: 416

Answers (4)

leemes
leemes

Reputation: 45675

Given that you really need to convert a pointer (which has to be correctly initialized, by the way...) to a char*, this isn't possible.

You can only implement operators for values (or references) of your class within the class. Some operators can be defined outside of the class, but casting operators aren't (for example, operator+ can be implemented outside, taking two parameters).

Given the fact that arithmetic operators can be implemented outside of classes (operator<< is an arithmetic operator), you can implement a stream operator for output to, for example, std::cout, even with pointers.

std::ostream & operator <<(std::ostream & o, const test & t) {
    return o << t.toString();  // use std::string here, not c-strings!
}
std::ostream & operator <<(std::ostream & o, const test * t) {
    return o << t->toString(); // use std::string here, not c-strings!
}

See live: http://ideone.com/BZfcji

Upvotes: 1

rmhartog
rmhartog

Reputation: 2323

You can store your heap object as a reference, instead of as a pointer.

test *my_heap_object = new test();
test &t = *my_heap_object;
// now you can use 't', as if it was local,
// instead of dereferencing the pointer each time.
printf(t);
t.do_something();
t++;

Some more explanation can be found on wikipedia.

Upvotes: 0

fredoverflow
fredoverflow

Reputation: 263138

An implicit conversion to char* may sound like a good idea, but trust me, it isn't. Guess why std::string doesn't have one. Just write a c_str method and call printf("%s", t->c_str()). Or even better, overload operator<< for your class. If you show us the class, we can help you.

Upvotes: 5

Tony The Lion
Tony The Lion

Reputation: 63200

You need to allocate memory to test *t before you can use it, else your pointer doesn't point to any memory.

You do it like so:

test * t= new test();

you'll also have to release it again when you're done:

delete t;

Also what of *t are you trying to print with printf? The address it points to, or some content of it's members? If the latter, you should overload an appropriate operator to do so.

Another thing, don't use printf in C++. Use std::cout and overload operator<< on your test class.

Upvotes: 0

Related Questions