I have an object of a base class which is actually pointing to a derived class like this
Base *b = new Derived()
What I want to know, is it possible to pass the base class pointer by reference to some function which can cast the object back to Derived class. Something like this
Dummy_cast_fn(&b) // casts b to derived class
After calling Dummy_cast_fn, b should have a full copy of Derived class (no slicing).
Edit
I dont understand the part that there is no slicing since pointers are used. My problem is Derived class is returned from a function call to a shared library and I do not have access to .h file for the Derived. Only information I have is that Derived is based on Base class. I have access to Base.h so I can instantiate an object of Base but problem comes when I try to access the functions which are defined in Derived but not in Base. So I was wondering if I can typecast the Base to Derived type, then I will be able to access the function defined in Derived and not in Base.
As long as
bis a pointer or reference to aDerived, you can always:Derived.Baseas long as you’re usingb.Namely, what determines what you can do with
bis its static type, in this caseBase. However, since it actually points on aDerived, you can always downcast it. Yet, to use it as aDerivedyou must have a variable whose type isDerivedas well.So, if the purpose of
Dummy_cast_fnis just to fix something inb– it’s useless. If an object is sliced, nothing can fix it. But in your case, there’s no slicing, since you’re using pointers.Edit according to the question’s edit:
First, you’re
Derivedobject is not sliced. Let’s get that off the table. You have a pointer to a completeDerived(assuming that’s what you’ve been passed), but you only have access to itsBasepart when using theBasepointer. Now, you say you don’t have the definition ofDerived. This means you won’t be able to downcast to that type, because the compiler doesn’t know how it’s defined. No casting will work here. There’s no legal C++ way you can call thatsumfunction if you don’t haveDerived‘s definition.I do wonder why the author of
Derivedprovided you its documentation without providing its definition. With this kind of polymorphism, the provider usually lets the user have some “interface”, leaving the actual type as an internal implementation detail. If you can’t useDerivedbecause you don’t have its definition, there’s no point in letting you have its documentation.