First, the question is very similar to downcasting shared pointer to derived class with additional functionality is, where there are good answers. But I'd like to have explanation on why this is valid (or not) and when not using shared pointers. So :
class Base { /* ... */ };
class Derived : public Base
{
public:
void additionnalFunc(int i){ /* access Base members */ }
};
int main(){
Base b;
Derived* d = (Derived*) &b; // or static_cast ?
d->additionnalFunc(3); // works ok.
}
This works as expected with gcc. So my question is it safe/valid ? with any compiler or architecture ? if not, why ?
To explain why this question, here is the context.
- I have "Base" objects.
- I can't modify the Base class
- I have a set of templated functions which requires the same interface as Base, except a few additional functions.
- I want to be able to use this templated library with my Base objects
- Because of the additional functions, the above is impossible. But these functions are trivial to implement from Base.
- Also I want to be as efficient as possible (avoid conversions and indirections)
So if the above trick is valid, it could be a good solution... But maybe there is a better design to solve this issue ?