Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way in C++ to preinitialize structure or class without a constructors?

I mean: I've a bunch of various structures/classes and all this a splendor shall be initialized with known in advance values. Those structures/classes will never be used other way except the preinitialized one, so there is no any need for constructor -- it's just a waste of extra memory, extra CPU cycles in program, and extra space in source code.

like image 671
Hi-Angel Avatar asked Jan 16 '26 21:01

Hi-Angel


2 Answers

If you have access to a C++11 compiler, you can mark your constructors as constexpr to have them run at compile time. The benefit of this is that way down the road you can still construct your objects at runtime. e.g.

struct Point2D {
    constexpr Point2D(int x, int y) : x_{x}, y_{y} {}
    int x_, y_;
};

And now you can use Point2D's constructor to initialize it at compile time, instead of runtime:

Point2D p{3, 4}; // no runtime overhead.
like image 187
bstamour Avatar answered Jan 19 '26 11:01

bstamour


Structures and classes can be initialized, in limited circumstances.

struct splendor {
    int i, j;
    char *name;
};

splendor iforus = { 1, 2, "Extra!" };

Additionally, if you never need the name of the type of the structure:

struct {
    int k;
    float q;
} anon_e_mouse = { 1, 2.3 };
like image 41
Robᵩ Avatar answered Jan 19 '26 09:01

Robᵩ



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!