C++ Interfaces

Started by
1 comment, last by Hodgman 8 years, 5 months ago

I'm looking for some help. Basically, I am trying to make a class called RenderPackage, which would contain a shader and a few other items.
But for this example, I am focused on the shader part.

In the RenderPackage, the shader member would be some type of shader. EG a default shader, a red light shader, and etc
Here I figured a Interface would work best, where all of my shaders would be able to implement this interface

So (I think) I made a interface for my shaders:


class IShader
{
public:
   virtual ~IShader();
   virtual void Use() = 0;
};

Then I have my render package:


class RenderPackage
{
public:
   IShader shader;
};

But I am getting an error for my RenderPackage class:
object of abstract class type "IShader" is not allowed. Function "IShader::Use" is a pure virtual function

So my question is:
How should I really be doing this? How can you use a Interface class as a member.
I was hoping I would be able to do something like:


DefaultShader defaultShader;
 
RenderPackage package;
package.shader = defaultShader;
 
//Down the line
package.shader.Use();
Advertisement

You would store a (smart) pointer to the interface type. So IShader * or something like std::shared_ptr<IShader>.

^to illustrate:
class RenderPackage
{
public:
// IShader shader; This says to create an instance of an IShader object!
   IShader* shader; //This says to create a variable that points to an instance of this interface
};

DefaultShader defaultShader;
 
RenderPackage package;
//package.shader = defaultShader; This says to slice the DefaultShader object and copy just the IShader members by value
package.shader = &defaultShader;//This points the 'shader' variable at our instance of the interface
See: http://www.google.com/search?q=object+slicing+c%2B%2B

This topic is closed to new replies.

Advertisement