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.
So if the above trick is valid, it could be a good solution... But maybe there is a better design to solve this issue ?
This is undefined behaviour. Whether it "works" or not on any given compiler is probably besides the point; you cannot rely on this working in general.*
In the scenario you've described, it sounds like the best solution is just to create some free functions that take a Base
as an argument. Of course, if the required functionality relies on protected
members, then you have a problem! (And I'm not sure there's a good solution, other than to find a way to avoid needing such access.)
(Of course, I'm not going to to suggest that this will definitely happen, merely that it could.)