Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating static constructors in C++?

Tags:

c++

syntax

Is there anyway I can modify this code example

#include <stdlib.h>
#include <iostream>

class Base {
public:
    Base() {
        if(!m_initialized) {
            static_constructor();
            m_initialized = true;
        }
    }
protected:
    virtual void static_constructor() {
        std::cout << "Base::static_constructor()\n";
    }
private:
    static bool m_initialized;
};

bool Base::m_initialized = false;

class Derived : public Base {
    void static_constructor() {
        std::cout << "Derived::static_constructor()\n";
    }
};

int main(int argc, char** argv) {
    Derived d;
    return(EXIT_SUCCESS);
}

So that Derived::static_constructor() gets called instead of the Base's? I want to initialize a bunch of static variables, and the most logical place to do it is somewhere in the class.

like image 207
mpen Avatar asked Jun 06 '26 22:06

mpen


1 Answers

You should never call virtual functions from the constructor (or destructor)! The result will not be as "expected" (hence the result you see). Why? Because the base constructor (Base) is called before the Derived constructor. This means that the local datamembers in Derived, which the virtual function may refer to, are not initialized yet. In addition, and maybe even more importantly, the vtable has not been initialized with functions in Derived yet, only with members from Base. Hence, the virtual function isn't really virtual yet - it won't be untill Base() completes and Derived() is processed.

Also, doing this would break the Open/Closed-principle which in short reads "classes should be open for extension, but closed for modification". You are by altering the Base static initialization trying to modify its behavior rather than extending it. It might seem like a good idea at the time, but chances are it will bite your ass later on ;)

like image 193
larsmoa Avatar answered Jun 08 '26 12:06

larsmoa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!