views:

88

answers:

2
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 should be fully constructed, but I wanted to check just in case.

+7  A: 

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.

sbi
A: 

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

adf88
That's plain wrong. There's certainly no problem with overloaded functions and constructors. Do you mean _overridden_? (And if so, don't forget that this applies to virtual functions only.)
sbi
upvoted (and sbi's answer too), but you mean 'overridden', not 'overloaded'
tpdi
sbi, in adf88's defense, overridden implies virtual (as otherwise it's hidden, not overridden, and probably a mistake).
tpdi
Even though the answer has been edited to talk about _overridden_ and not _overloaded_, it still doesn't explain _what_ the "danger" is. It could be a lot more helpful.
Charles Bailey
Corrected. I always mix these two words ;)
adf88
@tpdi: Look at this: `struct B { void f() {} }; struct D : B { void f() {} };` `D::f()` is certainly overriding `B::f()`. Although that's rarely ever what you want, in C++ there's overriding without `virtual`.
sbi