C++ Cast sub-sub class to base












2















With the classes below:



enum class OBJECT_TYPE {TYPE_1, TYPE_2, TYPE_3};

class BaseClass {
public:
BaseClass();
virtual ~BaseClass();
OBJECT_TYPE getObjectType() { return m_objectType; }
protected:
OBJECT_TYPE m_objectType;
}

class ChildClass : public BaseClass {
public:
ChildClass();
virtual ~ChildClass();
virtual void init() = 0;
protected:
// some other variables
}

class ChildChildClass : public ChildClass {
public:
ChildChildClass ();
~ChildChildClass ();
void init() override { m_objectType = OBJECT_TYPE::TYPE_3 }
private:
// some other variables
}


In a separate part of the code base, how would I cast a void* to a ChildChildClass instance to a BaseClass* such that I can call getObjectType() to determine which type of object it points to. I'm currently doing this:



(someOtherMethod() returns a void* to a ChildChildClass)



void* initialPointer = someOtherMethod();
BaseClass* basePointer = static_cast<BaseClass>(initialPointer);
if (basePointer->getObjectType() == OBJECT_TYPE::TYPE_3) {
ChildChildClass* childChildPointer = static_cast<ChildChildClass*>(basePointer);
}


I think I may be misunderstanding casting pointers when using inheritance, as I'm getting nonsense values for the returned objectType so any advice or info would be appreciated!










share|improve this question























  • Why are you using void* and not BaseClass *? Note it is undefined behaviour to cast a void* pointer to anything else but the exact original type it was obtained from. So (BaseClass*)(void*)childClassInstance is UB. And where's multiple inheritance?

    – n.m.
    Nov 24 '18 at 21:25













  • assuming that you really called 'init()' before converting it to void*. Otherwise m_objType is not initialized.

    – Serge
    Nov 24 '18 at 21:40


















2















With the classes below:



enum class OBJECT_TYPE {TYPE_1, TYPE_2, TYPE_3};

class BaseClass {
public:
BaseClass();
virtual ~BaseClass();
OBJECT_TYPE getObjectType() { return m_objectType; }
protected:
OBJECT_TYPE m_objectType;
}

class ChildClass : public BaseClass {
public:
ChildClass();
virtual ~ChildClass();
virtual void init() = 0;
protected:
// some other variables
}

class ChildChildClass : public ChildClass {
public:
ChildChildClass ();
~ChildChildClass ();
void init() override { m_objectType = OBJECT_TYPE::TYPE_3 }
private:
// some other variables
}


In a separate part of the code base, how would I cast a void* to a ChildChildClass instance to a BaseClass* such that I can call getObjectType() to determine which type of object it points to. I'm currently doing this:



(someOtherMethod() returns a void* to a ChildChildClass)



void* initialPointer = someOtherMethod();
BaseClass* basePointer = static_cast<BaseClass>(initialPointer);
if (basePointer->getObjectType() == OBJECT_TYPE::TYPE_3) {
ChildChildClass* childChildPointer = static_cast<ChildChildClass*>(basePointer);
}


I think I may be misunderstanding casting pointers when using inheritance, as I'm getting nonsense values for the returned objectType so any advice or info would be appreciated!










share|improve this question























  • Why are you using void* and not BaseClass *? Note it is undefined behaviour to cast a void* pointer to anything else but the exact original type it was obtained from. So (BaseClass*)(void*)childClassInstance is UB. And where's multiple inheritance?

    – n.m.
    Nov 24 '18 at 21:25













  • assuming that you really called 'init()' before converting it to void*. Otherwise m_objType is not initialized.

    – Serge
    Nov 24 '18 at 21:40
















2












2








2


1






With the classes below:



enum class OBJECT_TYPE {TYPE_1, TYPE_2, TYPE_3};

class BaseClass {
public:
BaseClass();
virtual ~BaseClass();
OBJECT_TYPE getObjectType() { return m_objectType; }
protected:
OBJECT_TYPE m_objectType;
}

class ChildClass : public BaseClass {
public:
ChildClass();
virtual ~ChildClass();
virtual void init() = 0;
protected:
// some other variables
}

class ChildChildClass : public ChildClass {
public:
ChildChildClass ();
~ChildChildClass ();
void init() override { m_objectType = OBJECT_TYPE::TYPE_3 }
private:
// some other variables
}


In a separate part of the code base, how would I cast a void* to a ChildChildClass instance to a BaseClass* such that I can call getObjectType() to determine which type of object it points to. I'm currently doing this:



(someOtherMethod() returns a void* to a ChildChildClass)



void* initialPointer = someOtherMethod();
BaseClass* basePointer = static_cast<BaseClass>(initialPointer);
if (basePointer->getObjectType() == OBJECT_TYPE::TYPE_3) {
ChildChildClass* childChildPointer = static_cast<ChildChildClass*>(basePointer);
}


I think I may be misunderstanding casting pointers when using inheritance, as I'm getting nonsense values for the returned objectType so any advice or info would be appreciated!










share|improve this question














With the classes below:



enum class OBJECT_TYPE {TYPE_1, TYPE_2, TYPE_3};

class BaseClass {
public:
BaseClass();
virtual ~BaseClass();
OBJECT_TYPE getObjectType() { return m_objectType; }
protected:
OBJECT_TYPE m_objectType;
}

class ChildClass : public BaseClass {
public:
ChildClass();
virtual ~ChildClass();
virtual void init() = 0;
protected:
// some other variables
}

class ChildChildClass : public ChildClass {
public:
ChildChildClass ();
~ChildChildClass ();
void init() override { m_objectType = OBJECT_TYPE::TYPE_3 }
private:
// some other variables
}


In a separate part of the code base, how would I cast a void* to a ChildChildClass instance to a BaseClass* such that I can call getObjectType() to determine which type of object it points to. I'm currently doing this:



(someOtherMethod() returns a void* to a ChildChildClass)



void* initialPointer = someOtherMethod();
BaseClass* basePointer = static_cast<BaseClass>(initialPointer);
if (basePointer->getObjectType() == OBJECT_TYPE::TYPE_3) {
ChildChildClass* childChildPointer = static_cast<ChildChildClass*>(basePointer);
}


I think I may be misunderstanding casting pointers when using inheritance, as I'm getting nonsense values for the returned objectType so any advice or info would be appreciated!







c++ multiple-inheritance






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 24 '18 at 20:47









RHSmith159RHSmith159

61039




61039













  • Why are you using void* and not BaseClass *? Note it is undefined behaviour to cast a void* pointer to anything else but the exact original type it was obtained from. So (BaseClass*)(void*)childClassInstance is UB. And where's multiple inheritance?

    – n.m.
    Nov 24 '18 at 21:25













  • assuming that you really called 'init()' before converting it to void*. Otherwise m_objType is not initialized.

    – Serge
    Nov 24 '18 at 21:40





















  • Why are you using void* and not BaseClass *? Note it is undefined behaviour to cast a void* pointer to anything else but the exact original type it was obtained from. So (BaseClass*)(void*)childClassInstance is UB. And where's multiple inheritance?

    – n.m.
    Nov 24 '18 at 21:25













  • assuming that you really called 'init()' before converting it to void*. Otherwise m_objType is not initialized.

    – Serge
    Nov 24 '18 at 21:40



















Why are you using void* and not BaseClass *? Note it is undefined behaviour to cast a void* pointer to anything else but the exact original type it was obtained from. So (BaseClass*)(void*)childClassInstance is UB. And where's multiple inheritance?

– n.m.
Nov 24 '18 at 21:25







Why are you using void* and not BaseClass *? Note it is undefined behaviour to cast a void* pointer to anything else but the exact original type it was obtained from. So (BaseClass*)(void*)childClassInstance is UB. And where's multiple inheritance?

– n.m.
Nov 24 '18 at 21:25















assuming that you really called 'init()' before converting it to void*. Otherwise m_objType is not initialized.

– Serge
Nov 24 '18 at 21:40







assuming that you really called 'init()' before converting it to void*. Otherwise m_objType is not initialized.

– Serge
Nov 24 '18 at 21:40














3 Answers
3






active

oldest

votes


















3














I'll ignore the numerous issues with such a design and just assume that you have a very good reason (i.e. can't change the design) for wanting to do what you're asking for. If you know that someOtherMethod() returns a void* that points to a ChildChildClass object, then you can first static_cast that void* to a ChildChildClass* and then either perform an explicit upcast to a BaseClass* or just use that ChildChildClass* as a BaseClass* since it can implicitly be converted anyways (there should be no need to perform an upcast just for the purpose of calling the method since ChildChildClass publicly derives from BaseClass):



ChildChildClass* initialPointer = static_cast<ChildChildClass*>(someOtherMethod());
BaseClass* basePointer = static_cast<BaseClass*>(initialPointer);


However, based on your code above, I am led to believe that you don't actually know that someOtherMethod() returns a pointer to a ChildChildClass object. Otherwise, why would you have to check whether it does before casting to ChildChildClass*? If you don't know the concrete type of object that the void* returned by someOtherMethod() points to, then there is no way to perform the cast you want to perform here (because there is know way of knowing what should actually be cast into what). One solution would be to change someOtherMethod() to always return a BaseClass* or at least a void* that you know for sure always points to a BaseClass object…






share|improve this answer


























  • Thanks so much for that! Unfortunately, I think I'm stuck with the void* as its coming from an external dependency (I'm trying to process Box2D collisions using callbacks, the physics body class b2Body has a void* variable which is used to store data about the game objects that are colliding, in this case, pointers to my classes, there are a few different types of object that could collide). This is really making me think about restructuring things, starting to think there must be a simpler way! So thank you for the information on pointers and for setting me on the right track! :)

    – RHSmith159
    Nov 24 '18 at 22:07






  • 2





    Yes, when interacting with APIs, you sometimes have to pass around void* pointers. In this case, make sure that you always know precisely what type that void* points to. Then you can always static_cast it back to what it was before you converted it to void*. You cannot convert back from void* and perform an up- or downcast at once because the up- or downcast may involve some pointer adjustments (e.g. when multiple inheritance is involved) that you would miss if you went straight from void* to the target type without going over the original pointer type.

    – Michael Kenzel
    Nov 24 '18 at 22:20





















1














You should use reinterpret_cast<> for casting from a void* :



 BaseClass* basePointer = reinterpret_cast<BaseClass*>(initialPointer);


But be extremely careful ! This is UB if the initialPointer would not point to an object of the correct type !



Additional recommendation:



For the down-casting, a safer approach would be to use dynamic_cast<>:



ChildChildClass* childChildPointer = dynamic_cast<ChildChildClass*>(basePointer);
if (! childChildPointer)
cout << "Something wrong happened !" <<endl;





share|improve this answer


























  • I think there should be no need for reinterpret_cast here, static_cast should be perfectly sufficient to cast void* to another object pointer type!?

    – Michael Kenzel
    Nov 24 '18 at 21:13













  • @MichaelKenzel yes, but reinterpret_cast would have the advantage to highlight that something risky is going on there. I edited and reformulated "need to" into "should", to take your point into consideration.

    – Christophe
    Nov 24 '18 at 21:17



















0














I would recommend using dynamic_cast.



// This is risky but I assume you know what you are doing.
// BTW, you are using static_cast<BaseClass>. That is not correct.
BaseClass* basePointer = static_cast<BaseClass*>(initialPointer);

// Now use dynamic_cast.
ChildChildClass* childChildPointer = dynamic_cast<ChildChildClass*>(basePointer);

if ( childChildPointer != nullptr)
{
// Use childChildPointer.
}
else
{
// Do something different.
}


It will be better if someOtherMethod can be modified to return a BaseClass*.



BaseClass* basePointer = someOtherMethod();


Then, rest of the code is unlikely to be a problem.






share|improve this answer


























  • @KamilCuk, I'm going to guess that my first version had a copy&paste error - static_cast<BaseClass>(initialPointer) instead of the correct one.

    – R Sahu
    Nov 24 '18 at 22:43













Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53462227%2fc-cast-sub-sub-class-to-base%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









3














I'll ignore the numerous issues with such a design and just assume that you have a very good reason (i.e. can't change the design) for wanting to do what you're asking for. If you know that someOtherMethod() returns a void* that points to a ChildChildClass object, then you can first static_cast that void* to a ChildChildClass* and then either perform an explicit upcast to a BaseClass* or just use that ChildChildClass* as a BaseClass* since it can implicitly be converted anyways (there should be no need to perform an upcast just for the purpose of calling the method since ChildChildClass publicly derives from BaseClass):



ChildChildClass* initialPointer = static_cast<ChildChildClass*>(someOtherMethod());
BaseClass* basePointer = static_cast<BaseClass*>(initialPointer);


However, based on your code above, I am led to believe that you don't actually know that someOtherMethod() returns a pointer to a ChildChildClass object. Otherwise, why would you have to check whether it does before casting to ChildChildClass*? If you don't know the concrete type of object that the void* returned by someOtherMethod() points to, then there is no way to perform the cast you want to perform here (because there is know way of knowing what should actually be cast into what). One solution would be to change someOtherMethod() to always return a BaseClass* or at least a void* that you know for sure always points to a BaseClass object…






share|improve this answer


























  • Thanks so much for that! Unfortunately, I think I'm stuck with the void* as its coming from an external dependency (I'm trying to process Box2D collisions using callbacks, the physics body class b2Body has a void* variable which is used to store data about the game objects that are colliding, in this case, pointers to my classes, there are a few different types of object that could collide). This is really making me think about restructuring things, starting to think there must be a simpler way! So thank you for the information on pointers and for setting me on the right track! :)

    – RHSmith159
    Nov 24 '18 at 22:07






  • 2





    Yes, when interacting with APIs, you sometimes have to pass around void* pointers. In this case, make sure that you always know precisely what type that void* points to. Then you can always static_cast it back to what it was before you converted it to void*. You cannot convert back from void* and perform an up- or downcast at once because the up- or downcast may involve some pointer adjustments (e.g. when multiple inheritance is involved) that you would miss if you went straight from void* to the target type without going over the original pointer type.

    – Michael Kenzel
    Nov 24 '18 at 22:20


















3














I'll ignore the numerous issues with such a design and just assume that you have a very good reason (i.e. can't change the design) for wanting to do what you're asking for. If you know that someOtherMethod() returns a void* that points to a ChildChildClass object, then you can first static_cast that void* to a ChildChildClass* and then either perform an explicit upcast to a BaseClass* or just use that ChildChildClass* as a BaseClass* since it can implicitly be converted anyways (there should be no need to perform an upcast just for the purpose of calling the method since ChildChildClass publicly derives from BaseClass):



ChildChildClass* initialPointer = static_cast<ChildChildClass*>(someOtherMethod());
BaseClass* basePointer = static_cast<BaseClass*>(initialPointer);


However, based on your code above, I am led to believe that you don't actually know that someOtherMethod() returns a pointer to a ChildChildClass object. Otherwise, why would you have to check whether it does before casting to ChildChildClass*? If you don't know the concrete type of object that the void* returned by someOtherMethod() points to, then there is no way to perform the cast you want to perform here (because there is know way of knowing what should actually be cast into what). One solution would be to change someOtherMethod() to always return a BaseClass* or at least a void* that you know for sure always points to a BaseClass object…






share|improve this answer


























  • Thanks so much for that! Unfortunately, I think I'm stuck with the void* as its coming from an external dependency (I'm trying to process Box2D collisions using callbacks, the physics body class b2Body has a void* variable which is used to store data about the game objects that are colliding, in this case, pointers to my classes, there are a few different types of object that could collide). This is really making me think about restructuring things, starting to think there must be a simpler way! So thank you for the information on pointers and for setting me on the right track! :)

    – RHSmith159
    Nov 24 '18 at 22:07






  • 2





    Yes, when interacting with APIs, you sometimes have to pass around void* pointers. In this case, make sure that you always know precisely what type that void* points to. Then you can always static_cast it back to what it was before you converted it to void*. You cannot convert back from void* and perform an up- or downcast at once because the up- or downcast may involve some pointer adjustments (e.g. when multiple inheritance is involved) that you would miss if you went straight from void* to the target type without going over the original pointer type.

    – Michael Kenzel
    Nov 24 '18 at 22:20
















3












3








3







I'll ignore the numerous issues with such a design and just assume that you have a very good reason (i.e. can't change the design) for wanting to do what you're asking for. If you know that someOtherMethod() returns a void* that points to a ChildChildClass object, then you can first static_cast that void* to a ChildChildClass* and then either perform an explicit upcast to a BaseClass* or just use that ChildChildClass* as a BaseClass* since it can implicitly be converted anyways (there should be no need to perform an upcast just for the purpose of calling the method since ChildChildClass publicly derives from BaseClass):



ChildChildClass* initialPointer = static_cast<ChildChildClass*>(someOtherMethod());
BaseClass* basePointer = static_cast<BaseClass*>(initialPointer);


However, based on your code above, I am led to believe that you don't actually know that someOtherMethod() returns a pointer to a ChildChildClass object. Otherwise, why would you have to check whether it does before casting to ChildChildClass*? If you don't know the concrete type of object that the void* returned by someOtherMethod() points to, then there is no way to perform the cast you want to perform here (because there is know way of knowing what should actually be cast into what). One solution would be to change someOtherMethod() to always return a BaseClass* or at least a void* that you know for sure always points to a BaseClass object…






share|improve this answer















I'll ignore the numerous issues with such a design and just assume that you have a very good reason (i.e. can't change the design) for wanting to do what you're asking for. If you know that someOtherMethod() returns a void* that points to a ChildChildClass object, then you can first static_cast that void* to a ChildChildClass* and then either perform an explicit upcast to a BaseClass* or just use that ChildChildClass* as a BaseClass* since it can implicitly be converted anyways (there should be no need to perform an upcast just for the purpose of calling the method since ChildChildClass publicly derives from BaseClass):



ChildChildClass* initialPointer = static_cast<ChildChildClass*>(someOtherMethod());
BaseClass* basePointer = static_cast<BaseClass*>(initialPointer);


However, based on your code above, I am led to believe that you don't actually know that someOtherMethod() returns a pointer to a ChildChildClass object. Otherwise, why would you have to check whether it does before casting to ChildChildClass*? If you don't know the concrete type of object that the void* returned by someOtherMethod() points to, then there is no way to perform the cast you want to perform here (because there is know way of knowing what should actually be cast into what). One solution would be to change someOtherMethod() to always return a BaseClass* or at least a void* that you know for sure always points to a BaseClass object…







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 24 '18 at 21:17

























answered Nov 24 '18 at 21:12









Michael KenzelMichael Kenzel

4,278719




4,278719













  • Thanks so much for that! Unfortunately, I think I'm stuck with the void* as its coming from an external dependency (I'm trying to process Box2D collisions using callbacks, the physics body class b2Body has a void* variable which is used to store data about the game objects that are colliding, in this case, pointers to my classes, there are a few different types of object that could collide). This is really making me think about restructuring things, starting to think there must be a simpler way! So thank you for the information on pointers and for setting me on the right track! :)

    – RHSmith159
    Nov 24 '18 at 22:07






  • 2





    Yes, when interacting with APIs, you sometimes have to pass around void* pointers. In this case, make sure that you always know precisely what type that void* points to. Then you can always static_cast it back to what it was before you converted it to void*. You cannot convert back from void* and perform an up- or downcast at once because the up- or downcast may involve some pointer adjustments (e.g. when multiple inheritance is involved) that you would miss if you went straight from void* to the target type without going over the original pointer type.

    – Michael Kenzel
    Nov 24 '18 at 22:20





















  • Thanks so much for that! Unfortunately, I think I'm stuck with the void* as its coming from an external dependency (I'm trying to process Box2D collisions using callbacks, the physics body class b2Body has a void* variable which is used to store data about the game objects that are colliding, in this case, pointers to my classes, there are a few different types of object that could collide). This is really making me think about restructuring things, starting to think there must be a simpler way! So thank you for the information on pointers and for setting me on the right track! :)

    – RHSmith159
    Nov 24 '18 at 22:07






  • 2





    Yes, when interacting with APIs, you sometimes have to pass around void* pointers. In this case, make sure that you always know precisely what type that void* points to. Then you can always static_cast it back to what it was before you converted it to void*. You cannot convert back from void* and perform an up- or downcast at once because the up- or downcast may involve some pointer adjustments (e.g. when multiple inheritance is involved) that you would miss if you went straight from void* to the target type without going over the original pointer type.

    – Michael Kenzel
    Nov 24 '18 at 22:20



















Thanks so much for that! Unfortunately, I think I'm stuck with the void* as its coming from an external dependency (I'm trying to process Box2D collisions using callbacks, the physics body class b2Body has a void* variable which is used to store data about the game objects that are colliding, in this case, pointers to my classes, there are a few different types of object that could collide). This is really making me think about restructuring things, starting to think there must be a simpler way! So thank you for the information on pointers and for setting me on the right track! :)

– RHSmith159
Nov 24 '18 at 22:07





Thanks so much for that! Unfortunately, I think I'm stuck with the void* as its coming from an external dependency (I'm trying to process Box2D collisions using callbacks, the physics body class b2Body has a void* variable which is used to store data about the game objects that are colliding, in this case, pointers to my classes, there are a few different types of object that could collide). This is really making me think about restructuring things, starting to think there must be a simpler way! So thank you for the information on pointers and for setting me on the right track! :)

– RHSmith159
Nov 24 '18 at 22:07




2




2





Yes, when interacting with APIs, you sometimes have to pass around void* pointers. In this case, make sure that you always know precisely what type that void* points to. Then you can always static_cast it back to what it was before you converted it to void*. You cannot convert back from void* and perform an up- or downcast at once because the up- or downcast may involve some pointer adjustments (e.g. when multiple inheritance is involved) that you would miss if you went straight from void* to the target type without going over the original pointer type.

– Michael Kenzel
Nov 24 '18 at 22:20







Yes, when interacting with APIs, you sometimes have to pass around void* pointers. In this case, make sure that you always know precisely what type that void* points to. Then you can always static_cast it back to what it was before you converted it to void*. You cannot convert back from void* and perform an up- or downcast at once because the up- or downcast may involve some pointer adjustments (e.g. when multiple inheritance is involved) that you would miss if you went straight from void* to the target type without going over the original pointer type.

– Michael Kenzel
Nov 24 '18 at 22:20















1














You should use reinterpret_cast<> for casting from a void* :



 BaseClass* basePointer = reinterpret_cast<BaseClass*>(initialPointer);


But be extremely careful ! This is UB if the initialPointer would not point to an object of the correct type !



Additional recommendation:



For the down-casting, a safer approach would be to use dynamic_cast<>:



ChildChildClass* childChildPointer = dynamic_cast<ChildChildClass*>(basePointer);
if (! childChildPointer)
cout << "Something wrong happened !" <<endl;





share|improve this answer


























  • I think there should be no need for reinterpret_cast here, static_cast should be perfectly sufficient to cast void* to another object pointer type!?

    – Michael Kenzel
    Nov 24 '18 at 21:13













  • @MichaelKenzel yes, but reinterpret_cast would have the advantage to highlight that something risky is going on there. I edited and reformulated "need to" into "should", to take your point into consideration.

    – Christophe
    Nov 24 '18 at 21:17
















1














You should use reinterpret_cast<> for casting from a void* :



 BaseClass* basePointer = reinterpret_cast<BaseClass*>(initialPointer);


But be extremely careful ! This is UB if the initialPointer would not point to an object of the correct type !



Additional recommendation:



For the down-casting, a safer approach would be to use dynamic_cast<>:



ChildChildClass* childChildPointer = dynamic_cast<ChildChildClass*>(basePointer);
if (! childChildPointer)
cout << "Something wrong happened !" <<endl;





share|improve this answer


























  • I think there should be no need for reinterpret_cast here, static_cast should be perfectly sufficient to cast void* to another object pointer type!?

    – Michael Kenzel
    Nov 24 '18 at 21:13













  • @MichaelKenzel yes, but reinterpret_cast would have the advantage to highlight that something risky is going on there. I edited and reformulated "need to" into "should", to take your point into consideration.

    – Christophe
    Nov 24 '18 at 21:17














1












1








1







You should use reinterpret_cast<> for casting from a void* :



 BaseClass* basePointer = reinterpret_cast<BaseClass*>(initialPointer);


But be extremely careful ! This is UB if the initialPointer would not point to an object of the correct type !



Additional recommendation:



For the down-casting, a safer approach would be to use dynamic_cast<>:



ChildChildClass* childChildPointer = dynamic_cast<ChildChildClass*>(basePointer);
if (! childChildPointer)
cout << "Something wrong happened !" <<endl;





share|improve this answer















You should use reinterpret_cast<> for casting from a void* :



 BaseClass* basePointer = reinterpret_cast<BaseClass*>(initialPointer);


But be extremely careful ! This is UB if the initialPointer would not point to an object of the correct type !



Additional recommendation:



For the down-casting, a safer approach would be to use dynamic_cast<>:



ChildChildClass* childChildPointer = dynamic_cast<ChildChildClass*>(basePointer);
if (! childChildPointer)
cout << "Something wrong happened !" <<endl;






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 24 '18 at 21:15

























answered Nov 24 '18 at 20:57









ChristopheChristophe

39k43476




39k43476













  • I think there should be no need for reinterpret_cast here, static_cast should be perfectly sufficient to cast void* to another object pointer type!?

    – Michael Kenzel
    Nov 24 '18 at 21:13













  • @MichaelKenzel yes, but reinterpret_cast would have the advantage to highlight that something risky is going on there. I edited and reformulated "need to" into "should", to take your point into consideration.

    – Christophe
    Nov 24 '18 at 21:17



















  • I think there should be no need for reinterpret_cast here, static_cast should be perfectly sufficient to cast void* to another object pointer type!?

    – Michael Kenzel
    Nov 24 '18 at 21:13













  • @MichaelKenzel yes, but reinterpret_cast would have the advantage to highlight that something risky is going on there. I edited and reformulated "need to" into "should", to take your point into consideration.

    – Christophe
    Nov 24 '18 at 21:17

















I think there should be no need for reinterpret_cast here, static_cast should be perfectly sufficient to cast void* to another object pointer type!?

– Michael Kenzel
Nov 24 '18 at 21:13







I think there should be no need for reinterpret_cast here, static_cast should be perfectly sufficient to cast void* to another object pointer type!?

– Michael Kenzel
Nov 24 '18 at 21:13















@MichaelKenzel yes, but reinterpret_cast would have the advantage to highlight that something risky is going on there. I edited and reformulated "need to" into "should", to take your point into consideration.

– Christophe
Nov 24 '18 at 21:17





@MichaelKenzel yes, but reinterpret_cast would have the advantage to highlight that something risky is going on there. I edited and reformulated "need to" into "should", to take your point into consideration.

– Christophe
Nov 24 '18 at 21:17











0














I would recommend using dynamic_cast.



// This is risky but I assume you know what you are doing.
// BTW, you are using static_cast<BaseClass>. That is not correct.
BaseClass* basePointer = static_cast<BaseClass*>(initialPointer);

// Now use dynamic_cast.
ChildChildClass* childChildPointer = dynamic_cast<ChildChildClass*>(basePointer);

if ( childChildPointer != nullptr)
{
// Use childChildPointer.
}
else
{
// Do something different.
}


It will be better if someOtherMethod can be modified to return a BaseClass*.



BaseClass* basePointer = someOtherMethod();


Then, rest of the code is unlikely to be a problem.






share|improve this answer


























  • @KamilCuk, I'm going to guess that my first version had a copy&paste error - static_cast<BaseClass>(initialPointer) instead of the correct one.

    – R Sahu
    Nov 24 '18 at 22:43


















0














I would recommend using dynamic_cast.



// This is risky but I assume you know what you are doing.
// BTW, you are using static_cast<BaseClass>. That is not correct.
BaseClass* basePointer = static_cast<BaseClass*>(initialPointer);

// Now use dynamic_cast.
ChildChildClass* childChildPointer = dynamic_cast<ChildChildClass*>(basePointer);

if ( childChildPointer != nullptr)
{
// Use childChildPointer.
}
else
{
// Do something different.
}


It will be better if someOtherMethod can be modified to return a BaseClass*.



BaseClass* basePointer = someOtherMethod();


Then, rest of the code is unlikely to be a problem.






share|improve this answer


























  • @KamilCuk, I'm going to guess that my first version had a copy&paste error - static_cast<BaseClass>(initialPointer) instead of the correct one.

    – R Sahu
    Nov 24 '18 at 22:43
















0












0








0







I would recommend using dynamic_cast.



// This is risky but I assume you know what you are doing.
// BTW, you are using static_cast<BaseClass>. That is not correct.
BaseClass* basePointer = static_cast<BaseClass*>(initialPointer);

// Now use dynamic_cast.
ChildChildClass* childChildPointer = dynamic_cast<ChildChildClass*>(basePointer);

if ( childChildPointer != nullptr)
{
// Use childChildPointer.
}
else
{
// Do something different.
}


It will be better if someOtherMethod can be modified to return a BaseClass*.



BaseClass* basePointer = someOtherMethod();


Then, rest of the code is unlikely to be a problem.






share|improve this answer















I would recommend using dynamic_cast.



// This is risky but I assume you know what you are doing.
// BTW, you are using static_cast<BaseClass>. That is not correct.
BaseClass* basePointer = static_cast<BaseClass*>(initialPointer);

// Now use dynamic_cast.
ChildChildClass* childChildPointer = dynamic_cast<ChildChildClass*>(basePointer);

if ( childChildPointer != nullptr)
{
// Use childChildPointer.
}
else
{
// Do something different.
}


It will be better if someOtherMethod can be modified to return a BaseClass*.



BaseClass* basePointer = someOtherMethod();


Then, rest of the code is unlikely to be a problem.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 24 '18 at 21:48

























answered Nov 24 '18 at 21:09









R SahuR Sahu

165k1291184




165k1291184













  • @KamilCuk, I'm going to guess that my first version had a copy&paste error - static_cast<BaseClass>(initialPointer) instead of the correct one.

    – R Sahu
    Nov 24 '18 at 22:43





















  • @KamilCuk, I'm going to guess that my first version had a copy&paste error - static_cast<BaseClass>(initialPointer) instead of the correct one.

    – R Sahu
    Nov 24 '18 at 22:43



















@KamilCuk, I'm going to guess that my first version had a copy&paste error - static_cast<BaseClass>(initialPointer) instead of the correct one.

– R Sahu
Nov 24 '18 at 22:43







@KamilCuk, I'm going to guess that my first version had a copy&paste error - static_cast<BaseClass>(initialPointer) instead of the correct one.

– R Sahu
Nov 24 '18 at 22:43




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53462227%2fc-cast-sub-sub-class-to-base%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

Calculate evaluation metrics using cross_val_predict sklearn

Insert data from modal to MySQL (multiple modal on website)