Question

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 ?

Était-ce utile?

La solution

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.)


* And that's true even if you never change your compiler. The compiler is free to assume that all code is "correct", so a slight change to your code may trigger an optimization that renders the above trick useless.

(Of course, I'm not going to to suggest that this will definitely happen, merely that it could.)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top