开发者

Calling base class method from derived constructor

class Base {
    public:
    Base() {}

    void Foo(int x) {...}
};

class Derived : public Base {
    public:
    Derived(int args) {
        /* process args in some way */

        Foo(result);
    }
};

Is it allowed to call a method of the base class in the constructor of the derived class? I would imagine this is fine as the Base object sh开发者_C百科ould be fully constructed, but I wanted to check just in case.


Is it allowed to call a method of the base class in the constructor of the derived class?

Yes. Just watch out for virtual functions. If an class derived from Derived overrides a virtual function, while constructing Derived as a sub-object of that further derived class, the dynamic type always is Derived, so no virtual functions overridden in further derived classes are called. (The same goes for the destructor, BTW.)

I would imagine this is fine as the Base object should be fully constructed, but I wanted to check just in case.

Your reasoning is right.


There is a danger when:
1. the method is overridden
2. the method calls other methods that are overridden

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜