My case is the following: In my larger program I want to make an interface to grab frames from a imagesource. However, in the program I do not know in advance whether I want to grab frames from a camera or from a video file. But I would like to have one interface that handles video files and camera frames as identical. This in total is is taking much code to accomplish, thus I'll present a very short example.
this is the example of the interface:
class Input {
public :
virtual void
get_frame() = 0;
};
This is a derived class that should grab frames from a camera.
class CameraInput: public Input {
public :
void get_frame();
};
This is the class that should open a videofile and grab frames from the file.
class VideoInput: public Input {
public :
void get_frame();
};
Here are the definitions of the get_frame
from the Input derived classes. As you can see they "produce" a different type of video frame.
void
CameraInput::get_frame(){
std::cout << "camera-frame" << std::endl;
};
void
VideoInput::get_frame() {
std::cout << "video-frame" << std::endl;
};
This it the code that instantiates an object of type CameraInput
or VideoInput
.
Edit shared pointer added
typedef enum { VIDEO, CAMERA } input_type ;
std::shared_ptr<Input> framegrabber;
/*Does this have to be a pointer?*/
/*In my program I don't know this in advance.*/
input_type my_input = CAMERA;
switch ( my_input ){
case CAMERA:
framegrabber = std::shared_ptr<Input>(new CameraInput);
break;
case VIDEO:
framegrabber = std::shared_ptr<Input>(new VideoInput);
break;
default:
/*error handling here*/
break;
};
framegrabber->get_frame();
On stackoverflow I read many times in c++ answers, that one should never use pointers unless one really, really needs to. This is where my question comes from, is it possible and better to rewite the code above without using a Input*
or is this one of the case where it is mandatory to use pointers?
kind regards,