Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forbid code to compile if some function is not called

Is there a way in C++ to forbid code to compile if the specific function was not called.

Imagine I have some class:

class CExample
{
public:
    void Init();
    void DoWork();

};

Is there a way to forbid calling DoWork() if the Init() function was not called for class object?

I want to forbid writing such a code:

CExample e;
e.DoWork();

and permit this version:

CExample e;
e.Init();
e.DoWork();

Can I reach this behaviour somehow with metaprogramming?

like image 440
ALEXANDER KONSTANTINOV Avatar asked Nov 29 '25 00:11

ALEXANDER KONSTANTINOV


2 Answers

You can just use a constructor instead of Init.

In his notes about exception safety in the standard library, as appendix to the 3rd edition of The C++ Programming Language, Bjarne Stroustrup discussed how using init functions is at odds with the notion of class invariant. It's generally Bad Practice™, mainly for that reason.

Some old GUI frameworks like Microsoft's MFC used init functions in order to do derived class specific initialization. There are other techniques to do that, including just passing the required information up the construction chain via arguments.

like image 63
Cheers and hth. - Alf Avatar answered Nov 30 '25 13:11

Cheers and hth. - Alf


No, that would be bad design. If it must be called for the object to be usable, it should be called in the constructor. After an object is constructed, all public methods should be callable-- the object should be fully constructed and ready for use.

like image 38
Rob K Avatar answered Nov 30 '25 15:11

Rob K



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!