This question is about overriding a virtual method in a derived class with a different return type.
For the following code:
class father {
public:
virtual father* ref() { return this; }
};
class child : public father {
virtual child* ref() { return this; }
};
When I try to get a pointer directly, g++ (F15, g++4.5) reports “invalid conversion from father to child”
child m_child;
father* pf = &m_child;
child* pc = pf->ref();
I understand the ref() method in the child class is used and this is probably just a compile time type mismatch.
However, is there any way to do it without explicitly use a type cast?
Extra description:
I understand the reason why compiler report this error. What I need is something out of the box which can access the data in derived object without explicitly convert a pointer.
The father class is used to put different derived child objects into lists or vectors, so when an item is fetch from the list or vector, there is no way to tell which child class it is belong to.
I have internal method to record and check the child class type. But I dont want to explicitly convert the pointer.
For example, I would like to do something like this:
// assuming pf is pointer pointed to an item fetch from a vector
switch(fp->get_type()) {
case child_type1: fp->ref()->list1.push(data); break;
case child_type2: fp->ref()->list2.push(data); break;
case child_type3: fp->ref()->list3.push(data); break;
}
Right now, I need to explicitly declare a new variable or explicitly convert fp to the proper type in each case and each time I need to access a data in derived classes, which are tedious and confusing.
What I expect are: may be some boost libraries can do similar things in another way which I dont know yet, or may be the c++11 standard allows it but a special compiling parameter needs to be set?
Simple answer is “no”.
You’ve lost the extra information (
child*rather thanfather*) aboutrefwhen you threw awaym_childs type information, by storing it as pointer to base (pf).One reason why it will never be possible without a cast is this example:
If you really want to make this doable without the dynamic cast you can just hide the dynamic cast (but it scares me a little)