The validity of casting a base pointer to a Derived pointer when Derived only adds methods

First of all, the question is very similar to a general pointer to a general class with additional functions , where there are good answers. But I would like to get an explanation of why this is valid (or not) and when the generic pointer is not used. 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 how safe / valid is it? with any compiler or architecture? if not, why?

To explain why this question, here is the context.

  • I have Base objects.
  • I can not change the base class
  • I have a set of template functions that require the same interface as Base, with the exception of a few additional functions.
  • I want to use this template library with basic objects
  • Due to additional functions, the above is not possible. But these functions are trivial to implement from the base.
  • I also want to be as effective as possible (avoid conversions and indirections)

So, if the above trick is valid, this might be a good solution ... But maybe there is a better design to solve this problem?

+2
source share
1 answer

This behavior is undefined. Whether this "works" or not on any compiler, perhaps beyond this; you cannot rely on this job at all. *

In the scenario you described, it seems like the best solution is to simply create some free functions that take Base as an argument. Of course, if the required functionality depends on the members of protected , then you have a problem! (And I'm not sure there is a good solution, except to find a way to avoid the need for such access.)


* And it's true even if you never change your compiler. The compiler may assume that all of the code is “correct,” so a small change in the code may cause optimizations that make this trick useless.

(Of course, I'm not going to assume that this will happen definitely , just so that I can ). Sub>

+2
source

Source: https://habr.com/ru/post/957249/


All Articles