I have a class template where some methods are defined as virtual to give the ability for the user of my class to give an implementation for them in his derived class. Note that in my template class there is some non-virtual methods that makes use of the virtual one (a virtual class that should return a value is called in a non-virtual class).
Can you give me a simple example of a correct code where the virtual method of the parent class should return a value (but it's implementation is provided in a child class) and the value returned by the virtual method in the parent class is used in other methods of that class. Because I saw somewhere (for example here: Safely override C++ virtual functions) that this can cause some problems and the user defined method will note override the virtual method of the parent class.
Note: I program with Code::Blocks using g++ compiler.
EDIT: as requested here a simple example of what I want:
template<typename T>
class parent {
public:
// Public methods that user can call
int getSomething(T t);
void putSomething(T t, int x);
// public method that user should implement in his code
virtual float compute(T t) { }
// protected or private methods and attributes used internally by putSomething ...
float doComplexeThings(...); // this can call
};
The method compute() should be implemented by the user (the child class). However, this method compute() is called by putSomething() and doComplexeThings() for example.
virtual float compute(T t)
. You simply use it (call it) inside putSomething() and doComplexeThings() viat.compute()
, if you have a handle to the instance. The compiler will error if your class T does not implement compute. In this way, parent and T actually do not even have to live in the same inheritance hierarchy: ie, T is a child of parent relationship is not required. Doing so also can give you a chance to give parent a more meaningful name (since the is-a relationship is not necessary). – Potfulfloat compute(...)
which is called bydoComplexeThings(...)
andputSomething(...)
, while the code of the methodfloat compute(...)
should be given by the user. – Cusack