Search code examples
c++inheritancecastingaccess-violation

Accessing member from casted generic pointer in derived class causes Access Violation


So I have a class called "TestScript" which is derived from the base class "Script". "Script" has a member called parent which is a generic pointer. In "TestScript" I have a member of type "GameObject" called "parentObj".

So what I am trying to do is cast the generic pointer from the "Script" base class into the "parentObj" member and access one if its "GameObject" members, but this causes an Access Violation.

I have stepped though the code and confirmed the line where I access the "name" member of the "GameObject" type is where the error occurs.

Here is the code:

"Script" class definition (In "Objects.cpp"):

class Script
{
public:
    void* parent = NULL; // The generic pointer
    virtual void Initialize() {} // Not used
    virtual void Update() {}
    virtual void OnDestruction() {} // Also not used
};

"TestScript" class definition:

#include "Objects.cpp"

class TestScript : public Script
{
public:
    GameObject *parentObj = static_cast<GameObject*>(parent); // Casting...
    TestScript() {}
    void Update() override
    {
        std::cout << parentObj->name << std::endl; // Access violation here.
    }
};

The "GameObject" type is also defined in "Objects.cpp"

The generic pointer is automatically set to a "GameObject" using the this keyword from an already declared "GameObject" somewhere else.


Solution

  • Possibly, you set "parent" value after the code GameObject *parentObj = static_cast<GameObject*>(parent); is executed (if I'm not wrong, it's executed after base constructor and before derived class ctor)

    Consider using a function:

    GameObject* GetparentObj ()
    {
        return static_cast<GameObject*>(parent);
    }