Hello all,
I am looking for elegant way to call children's method from parent class,
is at possible at all?
Thanks
Printable View
Hello all,
I am looking for elegant way to call children's method from parent class,
is at possible at all?
Thanks
Use virtual functions if they're appropriate. A parent class shouldn't have any knowledge of classes derived from it.
if the parent has declared a virtual, and the parent calls that method somewhere in the class, it will actually call the child class's override of the virtual. oops, just like gcdef said.
otherwise you might need to start thinking about call back maps etc.
Gcdef,Amleto, thanks for your advise,
so after some googling I found a solution that seems nice - using private inheritance
and pure virtual functions at the base class.
http://www.parashift.com/c++-faq-lit....html#faq-24.3
If private inheritance seems suitable for your case then probably, you should take the simpler route of composition. That would give you the flexibility of having 1-to-many relationship with the class and the member it is composed of. With private inheritance you would have a 1-1 relationship of the derived and the base object. But, the decision is yours, because we don't know what you are trying to do exactly. May be you don't need inheritance or may be you need public inheritance or may be you don't need virtual functions at all. Anything could be possible in the dark context we have.
I would like to show the simplified case which describes my goal.In general there is
some system with feedback, and the difference between data collecting and the feedback
is just in parameters.
There are many child classes of "Measurement", I just would' like them to deal with "Feedback", but just to decide what type
of "Measurement" to do - with feedback or without.
Something like that:
#include <iostream>
using namespace std;
typedef struct _PARAM {
char* param1;
char* param2;
} PARAM;
class Feedback {
protected:
virtual void get_measurement()=0;
public:
void Feedback_main() {
get_measurement();
}
};
class Measurement : private Feedback {
protected:
public:
Measurement *_feedbck;
char* str_out;
void get_measurement() {
cout << "get_measurement() with " << str_out << endl;
}
void get_measurement_with_Feedback(PARAM parameters) {
_feedbck = new Measurement;
str_out = parameters.param1;
get_measurement();
_feedbck->str_out=parameters.param2;
_feedbck->Feedback_main();
}
};
int main() {
Measurement *meas = new Measurement;
PARAM parameters;
parameters.param1="Measurement parameters";
parameters.param2="Feedback parameters";
meas->get_measurement_with_Feedback(parameters);
}
******************
the output is:
get_measurement() with Measurement parameters
get_measurement() with Feedback parameters
Actually you coding composition.Code:class Measurement : private Feedback {
protected:
public:
Measurement *_feedbck;
char* str_out;