Search code examples
c++inheritanceparent

C++: Losing access to memebers of a child class when converting child into the parent


First of all this is my first post so please be gentle. :)

I have a question (perhaps quite basic) but its quite specific and I couldn't find anything that would answer it.

I have created a Shader class that is a parent of a FacingRatioShader class. In the main.cpp I create an instance of a FacingRatioShader class and I pass it as a argument to an Object::addShader(Shader _shaderType) method:

void Object::addShader(Shader &_shaderType)
{
    m_shaderType = _shaderType;
}

And in the header of Object:

Shader m_shaderType;

The problem is that once the m_shaderType has been set it becomes a Shader type instead of FacingRatioShader type. Because of this I am loosing the ability to access the FacingRatioShader specific method called compute().

Is there anyway of creating the type for m_shaderType and modifying Object::addShader so that it can accept any child of a Shader class but still keeping the possibility to access the child methods?

I hope that my question is clear enough. If not please do not hesitate to ask me for more details.

Thanks in advance!

Regads, Dawid


Solution

  • The answer is partly yes, and partly no. You can change m_shaderType to store a pointer, but you will still only be able to call methods that are declared inside the parent class (so in Shader).

    If you want to call methods dependant on the class/subclass, declare them in the base class as virtual and overwrite their bodies inside child classes.

    class Object{
       Shader* m_shaderType;
       // ...
       void addShader(Shader &_shaderType)
       {
          m_shaderType = &_shaderType;
       }
       // ...
    };
    

    You could - theoretically - store information about what type did you pass to addShader (with an additional variable that you would set accordingly to recognize the child classes), but that's not a really good idea.