简体   繁体   中英

Call overridden method in parents constructor in C++

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 ).

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++".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM