C++ virtual method overriding [duplicate]
Asked Answered
G

2

7

Possible Duplicate:
Calling virtual functions inside constructors

main.cpp

#include <iostream>

class BaseClass {

    public:

    BaseClass() {
        init();
    }

    virtual ~BaseClass() {
        deinit();
    }

    virtual void init() {
        std::cout << "BaseClass::init()\n";
    }

    virtual void deinit() {
        std::cout << "BaseClass::deinit()\n";
    }

};

class SubClass : public BaseClass {

    public:

    virtual void init() {
        std::cout << "SubClass::init()\n";
    }

    virtual void deinit() {
        std::cout << "SubClass::deinit()\n";
    }

};

int main() {
    SubClass* cls = new SubClass;
    delete cls;
    return 0;
}

Why is init() and deinit() not properly overriden and the BaseClasses' methods are called instead of the SubClasses ones? What are the requirements to make it work?

BaseClass::init()
BaseClass::deinit()
Guenna answered 31/1, 2013 at 13:32 Comment(2)
@LightnessRacesinOrbit: Sorry for that. I didn't directly associate the problem with the constructor and destructor, which I guess was why I didn't find this question.Guenna
I guess the justification is that SubClass's constructor is allowed to assume that BaseClass is entirely constructed when it is executing. Similar for the destructor.Gorski
L
5

Because you are calling a virtual method inside a constructor. While constructing Base class the derived one (SubClass) isn't still constructed, so actually it doesn't still exist.

It's generally a good practice to avoid calling virtual methods inside constructors.

Lassie answered 31/1, 2013 at 13:34 Comment(0)
D
5

They are overridden just fine.

But you've invoked them from the base constructor, and when the base constructor is executing, the derived part of the object does not yet exist.

So this is a largely a safety feature, and it's mandated by the C++ standard.

Dorena answered 31/1, 2013 at 13:34 Comment(0)
L
5

Because you are calling a virtual method inside a constructor. While constructing Base class the derived one (SubClass) isn't still constructed, so actually it doesn't still exist.

It's generally a good practice to avoid calling virtual methods inside constructors.

Lassie answered 31/1, 2013 at 13:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.