[Grr... Google needs to make Groups work with the back button, at least
in Firefox. I hit a link by accident and lost most of this reply from
the first time I typed it. Anyway...]
The short answer is that you can't do it.
The medium answer is that you probably shouldn't do it. See BigBrian's
reply. If you post the context of what you're doing, we might be able
to help you come up with an alternate solution. (There are a couple
ideas below, after the long answer.) But you probably shouldn't have to
do this.
If you really want to do this, read on. There are a couple possible
solutions to do something sorta along the same lines as what you
want...
The long answer is that you can fake it. Make a union type, e.g.
typedef union { int number; string str; } string_or_int;
and return that. Depending on the type of variable you are storing the
result in, do like my_base_object.get_data().number or
my_base_object.get_data().str.
Actually, a better way is to make a discriminated union. It'll require
more typing because you'll have to define a class, but it's not too
hard. Add a union like above, then add another field that you can set
to indicate whether a number or string is stored in the union. Make a
get_integer() and a get_string() function that check this type before
returning, and throw an exception if the function call doesn't match
the type.
The longest answer is that an even better way is to drop the whole idea
in the first place. If you're going to go the route of the (possibly
discriminated) union, you might as well just put the two functions
right in the base class and do it that way. Something like this:
class base {
public:
virtual int get_child1_data() { throw someException("Class isn't a
child1"); }
virtual string get_child2_data() { throw someException("Class
isn't a child2"); }
}
class child1 {
...
public:
virtual int get_child1_data() { return data; }
}
(This is sorta hackish. There is probably a better way to do the same
idea. Actually, some might say the discriminated union idea is better.)
Another idea is if the string is going to be something like "123" you
could make the get function in child2 convert data to an integer and
return that; then the get function would be an int in each of its
occurances and it would all work out. Or, you could convert child1's
data to a string (so the integer 123 to the string "123") and return
that.
If this is still not flexible enough, perhaps you should consider
another language like Ruby where everything is a an object that derives
from one root and thus you don't have to worry about types in the same
sense as your typical imperative languages like C, C++, Java, C#, etc.,
only what operations (methods) the objects support. I think Smalltalk
would work too.