I have multiple classes derived from a single base class, and each derived class uses an identical computation function -- except for one variable that is dependent on the derived class. It would be nice to have this shared function written once in the base class and used by each derived class, while using the value from the derived class.
I'm wondering if there is a more obvious/intuitive or smarter way to do this than what I came up with.
I wrote a virtual "get" function in the base class, and filled that in for each derived class, so that the base class can call it in the shared computation function.
As a code example:
Base class:
Code:
/* base.hpp */
#ifndef BASE_H
#define BASE_H
class Base
{
private:
/* Defined in each Derived class to return a particular value */
virtual int getData() {};
public:
/* Do some computation using the Derived
* class' implementation of getData */
int computeThings() { return getData() * 123; };
};
#endif /* BASE_H */
Derived class:
Code:
/* derived.hpp */
#ifndef DERIVED1_H
#define DERIVED1_H
#include "base.hpp"
class Derived1 : public Base
{
private:
enum
{
/* This derived class uses a data value of 1, any
* other classes could use something else */
data = 1
};
int getData() { return data; };
public:
};
#endif /* DERIVED1_H */
So there could be a Derived1 class, a Derived2 class, and so on, each pulling in a different "data" variable when they use the Base class' computeThings() function.
This does what I need it to do, but I'm curious if there is a better way? Thanks for reading.