Reputation: 13
I have some code (C++11) like this:
Form.hpp:
class CForm{
public:
CForm(int paTemplate);
protected:
virtual void createFromTemplate(int paTemplate);
}
Dialog.hpp
class CDialog : public CForm {
public:
CDialog(int paTemplate);
private:
void createFromTemplate(int paTemplate);
};
Form.cpp
CForm::CForm(int paTemplate){
createFromTemplate(paTemplate);
}
Dialog.cpp
CDialog::CDialog(int paTemplate) : CForm(paTemplate){
active = false;
}
I want my dialog to call it's own createFromTemplate
, in this way the form's createFromTemplate
is called. How can I achieve it? (I call CDialog(template);
in my main
).
Upvotes: 0
Views: 81
Reputation: 6642
The problem here is that CDialog
is not yet created (remeber class construction order: from top to bottom), so there is no override for the function createFromTemplate
.
If you need the function to be virtual then I guess the best option is to add a new protected method in CForm
(lets call it initializeComponent
), which should be called from the constructor of CDialog
class CForm {
// .. stuff
protected:
virtual void createFromTemplate(int paTemplate);
void initializeComponent() {
createFromTemplate()
}
};
class CDialog: public CForm {
CDialog(...) : CForm(...) {
initializeComponent();
}
};
My 2 cents
Upvotes: 0
Reputation: 8860
This is not possible - when you call virtual function in constructor/destructor, the version from "this" class or below is called. In your case, it would always call CForm::createFromTemplate(), no matter what you do.
Check this link - http://www.artima.com/cppsource/nevercall.html - it's a chapter from "Effective C++".
Upvotes: 3