Sign in to follow this  
Neilo

Composing interfaces using other interfaces in C++

Recommended Posts

Neilo    290
I'm toying with a multiapi and maybe multiplatform rendering system abstraction and just have a C++ related query about interfaces. If I have the following abstract base classes:
class ISwapChain
{
public:
	virtual ~ISwapChain() {}
	virtual void Present() = 0;
};

class IRenderTarget
{
public:
	virtual ~IRenderTarget() {}
	virtual void SomeRenderTargetRelatedMethod() = 0;
};

class IRenderWindow : public ISwapChain, public IRenderTarget
{
public:
	virtual ~IRenderWindow() {}
	virtual void Resize(/* ... */);
	/* ... */
};
So I declare a D3D specific render window like this...
class D3DRenderWindow : public MyWin32Lib::Window /* Win32 specific window wrapper */, IRenderWindow
{
public:
	D3DRenderWindow() {}
	virtual ~D3DRenderWindow() {}
	
	// ISwapChain stuff
	void Present() {}
	
	// IRenderTarger stuff
	void Resize() {}
};
It all compiles and works but I've never really needed to composite "interfaces" together like this in C++ and I was wondering if it's a bad idea. The reason I want to do the above is so I can do something like this:
IRenderer* pRenderer = new Renderer(/* params including D3D, OGL, Software enum */);
IRenderWindow* = pRenderer->CreateWindow(/* some params */);
Note: I know the performance hit of using runtime polymorphism. This is just an experiment. My main framework uses templates to achieve a similar effect at compile time

Share this post


Link to post
Share on other sites
Faelenor    396
In C++, that's perfectly legal to implement multiple interfaces, just like in any object oriented language.

And about the performance hit of polymorphism, I think that in most cases, you shouldn't care too much about it. Especially for functions that are called just a couple of times per frame.

Share this post


Link to post
Share on other sites
jwezorek    2663
The way you are using multiple inheritance is standard practice. You're inheriting from abstract base classes so it's just like implementing an interface in Java -- nothing wrong or weird about that.

[Edited by - jwezorek on March 30, 2010 3:45:38 PM]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this