Manipulate behaviour of first ever constructor call from consecutive calls

57 Views Asked by At

I have to use C++98 for application i am developing for.

I want to control the behavior of constructor based on if it is a first ever call to constructor or not. For first ever constructor call, i want to execute some extra code but it must not execute in consecutive calls. For this I decided to have a static bool that will have default value of false, and after first constructor call, it will be set true for every other call.

class data_sender {
private:
    static bool library_initialized;
public: // etc.
};

This is kept private because i dont want consumer of this class to manipulate this directly. Its not const because obviously i want to change it inside constructor.

Now i cannot assign the default value for this, it says c++ forbids this non-const static variable initialization.

I think my approach is wrong here and i should be using some other method. I am relatively new to c++ so even if you point me to some article or tell me what to search for this.


Another strange thing i noticed is, when i define the library_initialized as false within the .h file,

class data_sender { .... };
bool data_sender::library_initialized = false;

it gives me linker error.

But if i define it inside the data_sender.cpp, it allows me to do this, and compiles without error.

data_sender::data_sender() { ... } //constructor definition
bool data_sender::library_initialized = false; // This is inside data_sender.cpp

This application is developed for mips and ipq architecture in mind, and will be compiled using gcc 4.8 (openwrt-mips) and gcc 5.2 (openwrt-arm) if that matters.


I found one answer on stackoverflow that is similar to mine, why is it required for me to specify this in implementation file only (.cpp) and not in header (.h).

Static constant string (class member)

0

There are 0 best solutions below