I'm trying to code a class to handle joystick input (irrelevant), and being rusty on inheritance and new to c++ I'm having some confusion while trying to create a subclass of my joystick class. Here's my code
//superclass's .h
#ifndef JOYSTICKINPUT_H
#define JOYSTICKINPUT_H
#include "WPILib.h"
class JoystickInput {
public:
JoystickInput(Joystick*);
Joystick * joystick;
Victor * myVictor [3];
bool buttons [10];
bool buttonClicked(int id);
void testForActions();
};
#endif
And here's its definition
//superclass's .cpp
#include "JoystickInput.h"
JoystickInput::JoystickInput(Joystick * joy) {
joystick = joy;
for (int x = 0; x < 10; x++) {
buttons[x] = false;
}
}
bool JoystickInput::buttonClicked(int id) {
if (buttons[id] == false and joystick->GetRawButton(id) == true) {
buttons[id] = true;
return true;
} else if (buttons[id] == true and joystick->GetRawButton(id) == false) {
buttons[id] = false;
return false;
} else {
return false;
}
}
void JoystickInput::testForActions() {
}
Now I'm trying to extend this with a JoystickOne class, as its behavior is slightly different. To this end I created a JoystickOne.h and a JoystickOne.cpp
//Joystickone.h
#ifndef JOYSTICKONE_H
#define JOYSTICKONE_H
#include "WPILib.h"
#include "JoystickInput.h"
class JoystickOne : public JoystickInput {
public:
JoystickOne(Joystick*);
Joystick * joystick;
Victor * myVictor;
bool buttons [10];
bool buttonClicked(int id);
void testForActions();
};
#endif
And the .cpp
#include "JoystickOne.h"
#include "WPILib.h"
JoystickOne::JoystickOne(Joystick * joy) : JoystickInput(joy) {
//joystick = joy;
//myVictor = new Victor(1);
/*for (int x = 0; x < 10; x++) {
buttons[x] = false;
}*/
}
bool JoystickOne::buttonClicked(int id) {
if (buttons[id] == false and joystick->GetRawButton(id) == true) {
buttons[id] = true;
return true;
} else if (buttons[id] == true and joystick->GetRawButton(id) == false) {
buttons[id] = false;
return false;
} else {
return false;
}
}
void JoystickOne::testForActions() {
if (buttonClicked(1)) {
}
if (buttonClicked(2)) {
}
if (buttonClicked(3)) {
//myVictor->Set(.3);
}
if (buttonClicked(4)) {
}
}
My problem is that I'm not quite sure what's extraneous in the JoystickOne class. I come from Java, so I'm used to being able to just extend a superclass and automatically use all of its methods and members. I'm confused because of C++'s seperation into .h and .cpp files; from what I've learned by messing around I have to declare all variables and methods I wish to use, even if they're members of the superclass. I don't think I have to define method buttonClicked() twice, although I don't have a robot so I can't actually test that now.
Basically, I'm asking what I can cut out from the definition of the JoystickOne class, and how to do it. If any of you have advice on some good OOP practices in C++ feel free to share, or maybe even clear up some java-isms that I have.
Thanks!
You should mark methods that can be overridden as virtual in your base class. To override it in a derived class, simply re-define it in your derived class.
Example:
class Base{
public:
virtual void overrideThis() { std::cout << "Base" << std::end; }
void test() { std::cout << "Base::test()" << std::endl; }
};
class Derived : public Base{
public:
void overrideThis() { std::cout << "Derived" << std::endl; }
};
Now if you instantiate:
Derived d;
d.overrideThis(); // Will print 'Derived'
d.test(); // Will print 'Base::test()'
As for member variables. Private members defined in your base will class will NOT be available in your derived class. On the other hand, protected and public member variables will be accessible.
You need to use the virtual keyword to make your functions inheritable. Furthermore, you can declare functions such as
buttonClicked(int id) = 0;
This will be the equivalent of an abstract methods.
You should not need to redefine variables, they should be automatically inherited if public or protected. Also note that you should declare your destructors virtual at all times, otherwise inherited classes will not be able to delete their own stuff.
No you don't have to re-declare the attributes in your inherited/child class, so remove those. Generally make them private (usable by parent class only) or protected (usable by parent and child classes) not public. With your methods, only 're-declare' them (override) if they act differently in the child class, and make sure you declare them virtual in the parent class. Experimenting is good.. remove some stuff, add lots of print statements, and see how it behaves :) It's not SO different from Java* apart from the .h/.cpp thing.
*At the basic level
Related
I have to modify my program and create a new (Gamefigures) class from which my current classes(Rabbit and Hedg) inherit. The code is a small game where two animals race until they reach the goal, but in the second task I have to make sure that it is possible that multiple iterations of these animals can race. (5 vs 5 or X vs X for instance). I am allowed to move some variables or methods to the Gamefigures class. Both of the animals use different rules to walk. How do I make a new class which creates multiple objects dynamically of the same class from which my current classes inherit?
I have tried to use the new expression to create a new object but I don't know if it is the right thing to do.
I tried:
Hedg* nHedg = new Hedg[numFigures];
Here is the rest of my code:
class Hedg: public Gamefigures
{
private:
int salat = 1;
protected:
int position1 = 0;
public:
bool turn(int fields)
{
int counter = 10;
if (fields < 11)//Less than 10 fields
{
while ((counter > 0))
{
if (counter < fields)//max 10 fields
{
fields = counter;
}
position1 += fields;//walk
counter -= fields;
if (counter <= 0)
{
salat = 0;
}
}
getSalat();
return true;
}
else
return false;
}
Hedg()
{
}
int getPosition1()
{
return position1;
}
int getSalat()
{
return salat = 1;
}
int getStock1()
{
return salat;
}
~Hedg()
{
}
};
class Game :public Hedg, public Rabbit
{
private:
int goal = 0;
int numFields = 0;
protected:
Rabbit theRabbit;
Hedg theHedg;
public:
Game();
Game(int numFields);
int getGoal();
int dice();
void doyourturn();
bool getStand();
~Game();
};
Here is the error message:
Error code C4430 missing typespecifier
I think that the polymorphism is what you need for your use case and will solve your problems.
Let's suppose you have a base class for your animals:
class Animal
{
// ...
// Create all the (pure) virtual methods to be redefined by a derived class
virtual void walk() = 0; // For example
};
Then you defines your two specific animals, the rabbit and the hedgehog:
class Rabbit : public Animal
{
// ...
// Redefine here the (pure) virtual methods of Animal for a Rabbit
void walk() override;
};
class HedgeHog : public Animal
{
// ...
// Redefine here the (pure) virtual methods of Animal for a HedgeHog
void walk override;
};
And you can use polymorphism to handle your list of animals:
std::vector<Animal*> race_competitors;
race_competitors.push_back(new Rabbit);
race_competitors.push_back(new HedgeHog);
And this way, when you will call the walk() method over a competitor, it will automatically execute the proper walking rule of the corresponding animal.
Of course, at the end of the race, don't forget to delete the content of the vector because the animals was created with new ("manually" allocated memory, on the heap).
Just for information, the Game class doesn't have to inherit from Rabbit and HedgeHog, it just has to know them as class members, or even better, store a std::vector<Animal*> as a list of competitors.
I hope it will help you to improve your design and solve your problems.
class MyObj{
public:
void myFunc(){
//ToBeExecutedJustOnce
}
};
I have a function that I want to be executable only once for the lifetime of MyObj. There may be many instances of MyObj, and each should be able to execute that function once. So if I have:
MyObj first;
MyObj second;
MyObj third:
first.myFunc(); // Should execute
second.myFunc(); // Should execute
third.myFunc(); // Should execute
first.myFunc(); // Should not execute
second.myFunc(); // Should not execute
third.myFunc(); // Should not execute
Options:
member variable: If I use a member variable, then other functions within MyObj can access it and change it.
global static variable: Can't work because first,second and third will all be checking the same variable.
local static: Same problem as #2.
The only solution I have found, is to have MyObj inherit from another class
MyOtherObj{
private:
bool _isInit = false;
public:
bool isInit(){
bool ret = true;
if (!_isInit){
ret = false;
_isInit = true;
}
return ret;
}
};
class MyObj : public MyOtherObj {
public:
void MyFunc(){
if (!isInit()){
//Do stuff...
}
}
};
Any better suggestion ?
EDIT: I don't care about thread safety!
EDIT: I do not want to execute the method in the constructor, simply because the method may need to be executed much later in the lifetime of the object....
Use std::once_flag. It is not resettable from other methods (then again, if you cannot trust other methods of the same class, your development process is highly questionable), easy to use, and it is even thread-safe if you ever do care about that. It can be a bit less efficient in a single-threaded program.
#include <mutex>
class MyObj {
public:
void MyFunc() {
std::call_once(initFlag, [=] {
//Do stuff...
});
}
private:
std::once_flag initFlag;
};
I don't see what is wrong with Option 1. If a class has so many responsibilities that another function may accidentally mess with the is_init member variable then the class should probably be made smaller.
However, if you want to encapsulate into another class that is less error prone, rather than using inheritance, I suggest you use composition:
class FirstTime {
bool first_time = true;
public:
bool operator()(){
if (!first_time)
return false;
first_time = false;
return true;
}
};
class MyObj {
FirstTime first_time;
public:
void myFunc(){
if (first_time()){
std::cout << "First time!\n";
}
}
};
Live demo.
As with Option 1, you should think about what copy/move behavior do you want. e.g Should a copy of an initialized MyObj be considered initialized?
I see three reasonable options:
Just use your option #1, a bool member variable.
Create a little class for an init flag, that can be set, but not be unset.
Use the public non-virtual interface (NVI) idiom, if you really want to be sure, that no-one messes with your flag.
A bool member variable
This would be my first choice. Make it private, of course. If your class has so many other data fields, that adding this new member appears painful, then this could be a sign of bad design of the entire class in the first place.
Often init() methods can be avoided completely by splitting up a class into two: A class A that contains the constructed data before the call to init() and a class B that is initialized upon construction. That way you can see if an object is initialized only by its type.
An init flag that can be set, but not reset
This class could look somewhat like this:
class InitFlag
{
public:
void set()
{
isSet_ = true;
}
operator bool() const
{
return isSet_;
}
private:
bool isSet_ = false;
};
This way, member functions cannot mess up your flag as easily. As an author of a class, you should be able to trust your member functions enough, that they don't set this flag, unless they are called init().
The non-virtual interface idiom
You create a base class with an init() function that is public and non-virtual. This function checks, if init() has been called before, calls a private purely virtual doInit() function which is supposed to do the actual initialization and sets the init flag after that. It looks like this:
class InitializeBase
{
public:
virtual ~InitializeBase() = default;
bool isInit() const
{
return isInit_;
}
void init()
{
assert( !isInit() );
doInit();
isInit_ = true;
}
private:
virtual void doInit() = 0;
bool isInit_ = false;
};
This has several security advantages:
Derived classes cannot modify isInit_.
Derived classes cannot call doInit(), as long as they don't make it public or protected (which would be very nasty). However, they can and must implement this function.
Hence doInit() function is statically guaranteed not to be called more than once, unless an assert() will trigger.
If you don't want the init() function to be public, then you can derive with the protected or the private attribute from InitializeBase.
The obvious drawback is that the design is more complicated and you get an additional virtual function call. For this reason the NVI idiom has become somewhat controversial.
Here's a variant that wraps a function in a class.
Once the function is called, it's replaced with one that does nothing.
const std::function<void()> nop = [](){};
class Once
{
public:
Once(std::function<void()> f) : m_function(f) {}
void operator()()
{
m_function();
m_function = nop;
}
private:
std::function<void()> m_function;
};
class Foo
{
public:
Foo(int x)
: m_function([this](){m_x += 1;}),
m_x(x) {}
int get() const { return m_x; }
void dostuff() { m_function(); }
private:
int m_x;
Once m_function;
};
int main()
{
Foo f(0);
cout << f.get() << endl; // 0
f.dostuff();
cout << f.get() << endl; // 1
f.dostuff();
cout << f.get() << endl; // 1
}
molbdnilo's answer is pretty good and was along the same lines I was thinking. I've changed a few things which I personally think makes it more idiomatic.
#include <iostream>
#include <functional>
class Once
{
bool isDone = false;
public:
void exec(std::function<void()> function)
{
if (!isDone)
{
function();
isDone = true;
}
}
};
class MyObj {
Once once = Once();
public:
void myFunc()
{
once.exec( []{
std::cout << "Hello, world!";
// do some stuff
});
}
};
int main()
{
MyObj foo = MyObj();
foo.myFunc();
foo.myFunc();
foo.myFunc();
}
The solution at the top is very good, but this might be a better solution for an interesting special case.
I assume that the method shall only be executed once because it modifies the state of the class. For the special case that the method initializes some parts of the class, I think it is best to use an optional, either boost::optional or std::optional or std::experimental::optional, depending on what is available to you:
#include <boost/optional.hpp>
class X
{
public:
void init()
{
if( ! _x )
{
_x.reset( 5 );
}
}
private:
boost::optional<int> _x;
};
I would like to create a simple framework for throwing and catching events in a game. Events could be things like a Collision which (according to the type) can take several arguments (note that every Event type may take another amount of arguments, not just two as in the example).
I would then like to implement functions/classes/... to deal with a Collision, based on polymorphism. This example should illustrate the problem:
#include <iostream>
#include <vector>
class Entity {};
class Player: public Entity {};
class Bomb: public Entity {
public:
bool exploded;
};
class MineSweeper: public Entity {};
// For now, I only included Collisions, but I eventually want to extend it to
// more types of Events too (base class Event, Collision is derived class)
void onCollision(Player* p, Bomb* b) {
if (! b->exploded) {
std::cout << "BOOM";
b->exploded = true;
}
}
void onCollision(Entity* e, Entity* f) {
std::cout << "Unhandled collision\n";
}
// Possibility for Collision between Minesweeper and Bomb later
class Game {
public:
std::vector<Entity*> board; // some kind of linear board
Game() {
board = {new Player, new Bomb, new MineSweeper};
}
void main_loop() {
onCollision(board[0], board[1]); // player and bomb!
onCollision(board[1], board[2]);
}
};
int main() {
Game g;
g.main_loop();
}
Note that I understand perfectly well why the above code doesn't work as intended, I included this example solely to illustrate my problem better.
The above example uses functions for the events, but I'm perfectly fine with classes or any other solution that is maintainable.
I hope it is clear that I would like C++ to decide which event handler to use based on the types of the arguments (presumably at runtime).
My question: How can I do this in C++? An example would be appreciated.
(not my question: fix my code please)
user2864740 provided enough clues for me to find a solution myself. Multiple dispatch was indeed the missing piece.
The following code works as intended, making use of dynamic_cast to dispatch correctly.
#include <iostream>
#include <vector>
class Entity {
virtual void please_make_this_polymorphic() {}
// although this function does nothing, it is needed to tell C++ that it
// needs to make Entity polymorphic (and thus needs to know about the type
// of derived classes at runtime).
};
class Player: public Entity {};
class Bomb: public Entity {
public:
bool exploded;
};
class MineSweeper: public Entity {};
// For now, I only included Collisions, but I eventually want to extend it to
// more types of Events too (base class Event, Collision is derived class)
void onCollision(Player* p, Bomb* b) {
if (!b->exploded) {
std::cout << "BOOM\n";
b->exploded = true;
}
}
void onCollision(Entity* e, Entity* f) {
std::cout << "Unhandled collision\n";
}
void dispatchCollision(Entity* e, Entity* f) {
Player* p = dynamic_cast<Player*>(e);
Bomb* b = dynamic_cast<Bomb*>(f);
if (p != nullptr && b != nullptr) {
onCollision(p, b); // player and bomb
} else {
onCollision(e, f); // default
}
}
class Game {
public:
std::vector<Entity*> board; // some kind of linear board
Game() {
board = {new Player, new Bomb, new MineSweeper};
}
void main_loop() {
dispatchCollision(board[0], board[1]); // player and bomb
dispatchCollision(board[1], board[2]);
}
};
int main() {
Game g;
g.main_loop();
}
Although it works, I'd like to point out some problems with this code:
Manual editing of dispatchCollision needed when adding new Collisions.
Currently, the dispatcher using a simple kind of rule-based system. (Does it fit rule 1? What about rule 2? ...) When adding loads of different functions it needs to dispatch, that may have an impact on the performance.
A collision between A and B should be the same as a collision between B and A, but that isn't properly handled yet.
Solving these problems is not necessarily in the scope of this question IMHO.
Also, the example given should work just as well for more than 2 arguments. (Multiple dispatch, not just double dispatch.)
You should decide first what event subscription model you need.
It could be signal/slot mechanism and you can find plenty of libraries:
https://code.google.com/p/cpp-events/ , http://sigslot.sourceforge.net/ and the like.
Or it could be bubbling/sinking events like in HTML DOM when event gets propagated on parent/child chain ( from event source element to its containers).
Or even other schema.
It is quite easy to create whatever you need with std::function holders in modern C++.
Maybe a good structure for your case could be something like this:
class Entity{
public:
virtual int getType() = 0;
};
enum EntityTypes {
ACTOR,
BOMB,
MINESWEEPER,
};
class Actor : public Entity{
public:
virtual int getType() {return int(ACTOR);}
void applyDamage() {
std::cout << "OUCH";
}
};
class Bomb : public Entity{
public:
Bomb() : exploded(false) {}
virtual int getType() {return int(BOMB);}
void explode() {
this->exploded = true;
}
bool isExploded() {
return this->exploded;
}
protected:
bool exploded;
};
class MineSweeper : public Entity{
public:
virtual int getType() {return int(MINESWEEPER);}
};
class CollisionSolver {
public:
virtual solve(Entity* entity0, Entity* entity1) = 0;
};
class ActorBombCollisionSolver : public CollisionSolver {
public:
virtual solve(Entity* entity0, Entity* entity1) {
Actor* actor;
Bomb* bomb;
if (entity0->getType() == ACTOR && entity1->getType() == BOMB) {
actor = static_cast<Actor*>(entity0);
bomb = static_cast<Bomb*>(entity1);
}else if (entity1->getType() == ACTOR && entity0->getType() == BOMB) {
actor = static_cast<Actor*>(entity1);
bomb = static_cast<Bomb*>(entity0);
}else {
//throw error;
}
if (!bomb->isExploded()) {
bomb->explode();
actor->applyDamage();
}
}
};
class CollisionDispatcher {
public:
CollisionDispatcher() {
CollisionSolver* actorBombCollisionSolver = new ActorBombCollisionSolver;
this->solvers[ACTOR][BOMB] = actorBombCollisionSolver;
this->solvers[BOMB][ACTOR] = actorBombCollisionSolver;
// this part wouldn't be necessary if you used smart pointers instead of raw... :)
this->solvers[BOMB][MINESWEEPER] = 0;
this->solvers[MINESWEEPER][BOMB] = 0;
this->solvers[ACTOR][MINESWEEPER] = 0;
this->solvers[MINESWEEPER][ACTOR] = 0;
}
void dispatchCollision(Entity* entity0, Entity* entity1) {
CollisionSolver* solver = this->solvers[entity0->getType()][entity1->getType()];
if (!solver) {
return;
}
solver->solve(entity0, entity1);
}
protected:
unordered_map<int, unordered_map<int, CollisionSolver*> > solvers;
};
class Game {
public:
std::vector<Entity*> board; // some kind of linear board
Game() : dispatcher(new CollisionDispatcher)
{
board = {new Player, new Bomb, new MineSweeper};
}
void main_loop() {
dispatcher->dispatchCollision(board[0], board[1]);
dispatcher->dispatchCollision(board[0], board[2]);
dispatcher->dispatchCollision(board[1], board[2]);
}
protected:
CollisionDispatcher* dispatcher;
};
int main() {
Game g;
g.main_loop();
}
This way you can easily add new collision solvers, just define the class, and register t in the CollisionDispatcher constructor.
If you use smart pointers you won't need to set zeroes in the map entries not registered, but if you use raw pointers you have to set them to zero OR use unordered_map::find method instead of just grabbing the solver using operator []
Hope it helps!
I have a large class with many methods. This class has a subclass that manages a different situation.
Just to clear it up with an example the actual situation is the following:
class Logic {
public:
virtual void method()
{
Something::getInstance()->doSomething();
}
};
class ArrayLogic : public Logic {
private:
Something** array;
public:
void method() override
{
for (int i = 0; i < AMOUNT; ++i)
array[i]->doSomething();
}
};
Now this pattern repeats itself in multiple methods and I'd like to have just one implementation without trading for performance (since some of this methods are actually already proven to require efficiency).
I was thinking if it's possible with C++11 to have a template solution approach which is able to manage this situation at compile time without the necessity to duplicate the code.
Mind that the array doesn't make sense to exist for Logic so having a Something*[1] is not a viable option.
An additional problem is that at the moment Something** array is not directly contained in ArrayLogic but resides in another class, so it's more like
class ArrayLogic : public Logic {
private:
Container* container;
public:
void method() override {
for (int i = 0; i < AMOUNT; ++i)
if (container->array[i])
container->array[i]->doSomething();
}
}
While having to check for container->array[i] != nullptr may seems strange the fact is that the position is relevant, so an element removed from the array doesn't cause a shift of the successive element but leaves a hole.
I'd try and create separate classes for single and multiplayer games. Base both of these on a base class LogicBase that has a method(Something*) function that calls doSomething() on its parameter. This is what #Pradhan was referring to.
In your main game, you can use a LogicBase* to refer to either a SinglePlayerLogic or a MultiPlayerLogic object and call the relevant method() using a virtual function call.
I'm passing what is stored in Container to the constructor of MultiPlayerLogic. But it could be in a separate class and accessed that way. Similarly, it may be cleaner to pass a Something to the constructor of SinglePlayerLogic, but I wanted to keep the code structure close to your original, so didn't do this.
It initially looks funny for LogicBase to call to a subclass, then have those subclasses call the protected method(Something*) back in the super class. I've seen it elsewhere as a design pattern, but can't recall it's name.
#include <iostream>
#include <vector>
const int AMOUNT = 5;
struct Something {
void doSomething() { std::cout << "Something::doSomething\n"; }
static Something* getInstance() { static Something s; return &s; }
};
class LogicBase {
public:
virtual void method() = 0;
protected:
void method(Something* s) { s->doSomething(); }
};
class SinglePlayerLogic : public LogicBase {
public:
void method() override
{
std::cout << "SinglePlayer::method\n";
LogicBase::method(Something::getInstance());
}
};
class MultiPlayerLogic : public LogicBase {
public:
MultiPlayerLogic(Something **s) : players(s) {}
void method() override
{
std::cout << "MultiPlayer::method\n";
for (int i = 0; i < AMOUNT; ++i) {
if (players[i] == nullptr) {
continue;
}
std::cout << i << " ";
LogicBase::method(players[i]);
}
}
private:
Something** players;
};
int main() {
LogicBase* lb;
SinglePlayerLogic spl;
lb = &spl;
lb->method();
std::vector<Something*> players{AMOUNT};
MultiPlayerLogic mpl(players.data());
lb = &mpl;
lb->method();
}
This is probably a basic question for a regular C++ user. Functionally, I have an ECG monitor, and want to choose which output format to use at runtime. I have set up two classes that expose the same methods and members (ECGRecordingDefaultFormat and ECGRecordingEDFFormat) eg. ->InsertMeasure, ->setFrequency, ->setPatientName etc.
I know I could define one instance of each format class type, then put in:
if (ECGFormatToUse == ECGFormat.EDF) {
ecgDefaultFormat.InsertMeasure(x);
}
if (ECGFormatToUse == ECGFormat.Default) {
ecgEDFFormat.InsertMeasure(x);
}
all throughout the code, but I think I might not be using C++'s dynamic typing to its full extent.
The question is: can I define just one variable in main(), and after choosing the format I want at runtime, have the code use the right class with its exposed 'InsertMeasure' method, avoiding a whole lot of if/else's throughout the code?
I'd be happy with just a reference to which aspect of inheritance/polymorphism (?) I should be using, and can google away the rest.
Thanks guys.
Pete
You can combine the factory pattern with C++'s polymorphism.
class Base
{
virtual void InsertMeasure() = 0; //virtual pure, make the base class abstract
};
class ECGRecordingDefaultFormat : public Base
{
virtual void InsertMeasure();
};
class ECGRecordingEDFFormat : public Base
{
virtual void InsertMeasure();
};
class Factory
{
static Base* create(ECGFormat format)
{
if ( format == ECGFormat.EDF )
return new ECGRecordingEDFFormat;
if ( format == ECGFormat.Default )
return new ECGRecordingDefaultFormat;
return NULL;
}
};
int main()
{
ECGFormat format;
//set the format
Base* ECGRecordingInstance = Factory::create(format);
ECGRecordingInstance->InsertMeasure();
return 0;
}
Others have already answered but I posted this as I had it written:
class EcgFormat
{
public:
virtual void InsertMeasure(int x) = 0;
};
class EcgFormatA : public EcgFormat
{
public:
void InsertMeasure(int x)
{
cout << "EcgFormatA: " << x << "\n";
}
};
class EcgFormatB : public EcgFormat
{
public:
void InsertMeasure(int x)
{
cout << "EcgFormatB: " << x << "\n";
}
};
class EcgFormatFactory
{
public:
static std::shared_ptr<EcgFormat> makeEcgFormat(char a_format)
{
switch (a_format)
{
case 'A':
return std::make_shared<EcgFormatA>();
break;
case 'B':
return std::make_shared<EcgFormatB>();
break;
default:
throw std::exception("Invalid format");
break;
}
}
};
int main()
{
std::shared_ptr<EcgFormat> format = EcgFormatFactory::makeEcgFormat('A');
format->InsertMeasure(5);
return 0;
}
(I know this pretty much the same as #Luchian answer).
Have an abstract super class EcgFormat (with several virtual methods kept abstract with =0) and several sub-classes ECGRecordingDefaultFormat, ECGRecordingEDFFormat etc