Sebastiaan van Dorst
Sebastiaan van Dorst

Reputation: 457

C++ how to make a class type more general and use it as a kind of interface

I have a class called "OpenGLCamera" and there is another class that needs a camera so at the moment he has OpenGLCamera (since the class is used as a type) like so:

void draw(const OpenGLCamera& camera);

But i want it to be more general, so i want it to be

void draw(const SomeCamera& camera);

and this "SomeCamera" should be a pointer/reference or something to OpenGLCamera ofcourse!

I have a class called "Visual_settings".. and i heared i should use inheritance to achieve this... but i dont understand how.. how to do this? in the class Visual_Settings? Make it a base class of... and then??

Visual_Settings.h

#include "OpenGLCamera.h"
class Visual_Settings : public OpenGLCamera
{

};

Thanks in advance

Upvotes: 2

Views: 121

Answers (2)

Abhijit-K
Abhijit-K

Reputation: 3679

The generic type that you are looking for which is SomeCamera, then OpenGLCamera should derive from this type SomeCamera. If you cannot do that then you need to use Adapter pattern. This would make sense if you have other types of cameras.

    class SomeCamera
    {
    public:
        virtual void Dowork()=0;
    };

    class OpenGLCamera : public SomeCamera
    {
    public:
        virtual void Dowork() override
        {
            //use camera
        }
    };

//Approach 2 (bridge pattern): when you cannot modify OpenGLCamera:

//***Use proper constructors/destructors and initialize base class constructors as required

    class SomeCamera
    {
    public:
        virtual void Dowork()=0;
    };

    class OpenGLCamera 
    {
    public:
       void OpenGlDowork() 
        {
            //use camera
        }
    };

    class OpenGLCameraAdapter : public SomeCamera, OpenGLCamera
    {
    public:
        virtual void Dowork() override
        {
            //use camera
            OpenGlDowork();

    }
};

Upvotes: 1

ForEveR
ForEveR

Reputation: 55887

  1. OpenGLCamera should be inherited from SomeCamera.
  2. SomeCamera should have interface, that will be overriden in OpenGLCamera.

Upvotes: 0

Related Questions