Thomas Heeley
Thomas Heeley

Reputation: 13

Forward Declaration and Accessing member functions in an inherited class

I am building a simple component architecture and have been struggling with a problem of forward declaration for a while

The component architecture is built as below

Component Class:

#pragma once
    class GameObject;

    class Component
    {
    public:
        Component();

        virtual ~Component();

        virtual void Start();

        virtual void Update(float _fDeltaTime);

        template<typename T>
        T* GetComponent()
        {
            T* c = m_GameObject->GetComponent<T>();
            return c;
        }

        GameObject& GetGameObject(); 

        void SetGameObject(GameObject& go);

    private:
        GameObject* m_GameObject;
    };

Game Object Classs

class GameObject
    {
    public:
        GameObject(std::string name);

        ~GameObject();

        template<typename T>
        T* GetComponent()
        {
            for (auto i : m_vecComponents)
            {
                T* c = dynamic_cast<T*>(i);

                if (c != nullptr)
                {
                    return c;
                }
            }
            return nullptr;
        }

        void AddComponent(std::string _strComponentName);

        void Start();

        void Update(float _fDeltatime);

    private:
        std::string m_Name;
        std::vector<Component*> m_vecComponents;
    };

Example Inherited Component, Sprite Renderer

class SpriteRenderer : public Component
{
public:
    SpriteRenderer();
    ~SpriteRenderer();

    void Start() override;
    void Update(float _fDeltaTime) override;

    void ChangeTexture(bool _bTextured);
    void SetColor();


private:
    Shader* m_pShader;
    Texture* m_pTexture;

    int m_iWidth;
    int m_iHeight;

    unsigned int m_iVAO;
    unsigned int m_iVBO;
    unsigned int m_iEBO;

    std::vector<float> m_vecVertices;
    std::vector<unsigned int> m_vecIndices;

    // Bools To Control Rendering
    bool m_bTexture;
};

These files all have an associated cpp file

The problem is I need to be able to get components from the game object inside the Sprite Renderer class, which causes issues because I have only forward declared Game Object, so I dont have access to those member functions.

Things I have tried

None of these solutions have worked, so any help I can get would be much appreciated

Upvotes: 0

Views: 73

Answers (1)

Thomas Heeley
Thomas Heeley

Reputation: 13

The problem was that SpriteRenderer.cpp Did not include GameObject.h

Upvotes: 1

Related Questions