Print names of polymorphic objects?

A

Angus

I am experimenting with polymorphism and have a list of polymorphic
objects. I want to be able to print out the list of objects. How do
I do this?

Do I need to implement eg an GetName member function? Or is there an
inbiult way to print? Eg some way to convert an object to a string
name?
 
T

ToMo

Angus said:
I am experimenting with polymorphism and have a list of polymorphic
objects. I want to be able to print out the list of objects. How do
I do this?

Do I need to implement eg an GetName member function? Or is there an
inbiult way to print? Eg some way to convert an object to a string
name?

http://en.wikipedia.org/wiki/Typeid
 
C

Christian Hackl

Angus said:
I am experimenting with polymorphism and have a list of polymorphic
objects. I want to be able to print out the list of objects. How do
I do this?

Do I need to implement eg an GetName member function?

That's one way of doing it.
Or is there an inbiult way to print?

Not really.
Eg some way to convert an object to a string name?

You can define a string conversion operator, e.g.:

class Person
{
public:
operator std::string() const { return name; }
private:
std::string name;
};

Person person;
std::string some_string = person;

Of course, this is not all that different from defining a "GetName"
member function, just that the syntactic shortcut may lead to unexpected
problems in certain situations, which is why you should use it with caution.


However, I think what you are really looking for is a way to send your
objects to an output stream like this:

std::cout << person;

You can achieve this by overloading operator<<. Here's more information
on how to implement it for a hierarchy of classes:

http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.11
 

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
473,774
Messages
2,569,598
Members
45,144
Latest member
KetoBaseReviews
Top