Structs and constructors (2024)

Table of Contents
Conclusion Connect deeper FAQs

Today, we are going to talk about when and why structs should have constructors if they should have them at all. We are also going to see once again that generic best practices and best practices to reduce binary size do not always go hand in hand.

I had some time to dedicate to cleaning up code. I remembered that recently I saw some structs like this:

1234
SomeSimpleStuct data;data.a_number = 42;data.a_character = 'a';return data;

I didn’t like this code. Even though the struct didn’t have any constructors, even though not all the members were set, with the help of designated initializers it’s so easy to get rid of the initialize then modify anti-pattern Connor Hoekstra talked about a couple of years ago at the Italian C++ conference.

1
return SomeSimpleStuct{.a_number = 42, .a_character = 'a'};

As a result, you get code that still tells you what is initialized, code which is more efficient without making it less readable and in addition you don’t have to think about why the object is created before its members are set.

Next, I checked some code where I did see some non-default constructors, probably because people wanted to avoid to previous pattern.

1234567891011121314
struct PileOfData { PileOfData() = default; explicit PileOfData(const std::string &type, const std::string &identifier = "") : type(type), identifier(identifier) {} std::string type; std::string identifier;};// Somewhere else...someVar.data = PileOfData("foo", "bar")// Yet another placePileOfData data("foobar");

I didn’t like this pattern either, because the members are public and we could initialize them directly. It’s true that it was not enough to simply remove the constructors, we had to modify the syntax. We could either use designated initializers which come along with aggregate initialization with its braces or if we didn’t need the member names in the initializer expressions, we could use simply braces.

123456789
struct PileOfData { std::string type; std::string identifier;};// Somewhere else...someVar.data = PileOfData{.type = "foo", .identifier = "bar"}// Yet another placePileOfData data{"foobar"};

So this shows that if you still haven’t upgraded to C++20, you can still use aggregate initialization without having to initialize all the members. If we provide n members in the initializer list, the first n member (counting from the top) will be initialized.

So unless the constructors are not initializing the first members of the struct (but they skip some in between), they didn’t make much sense from the beginning assuming that the code was not written to a standard earlier than C++11.

Then I continued looking for similar code and I found this.

1234567891011
struct AnotherPileOfData { std::string label; std::string remark; int quantity; AnotherPileOfData(const std::string& label, int quantity); AnotherPileOfData(const Blob& blob); DECLARE_DEFAULT_MEMBERS(AnotherPileOfData)};

Oh, a macro. There is even a corresponding implementation file, with other macro and constructor definitions.

123456
AnotherPileOfData::AnotherPileOfData(const std::string& label, int quantity): label(label), quantity(quantity) {}AnotherPileOfData::AnotherPileOfData(const Blob& blob): label(blob.label), remark(blob.text), quantity(blob.quantity) {}DEFINE_DEFAULT_MEMBERS(AnotherPileOfData)

That’s clearly not how most like to see their structs which should be simple. So I immediately started removing the fluff but I didn’t merge the changes. I didn’t even post a code review. Can you guess why?

Binary size was significantly impacted. Removing all the user-declared special member functions gave a few extra KBs for widely used classes. The reason is essentially inlining. With defaulted special member functions, each compilation unit where AnotherPileOfData is used, gets a copy of the special member functions’ code. In other words, they are inlined. With the used-provided versions, they are not inlined, but you get simple function calls.

I must say that if we didn’t care so much about binary sizes, I’d still go ahead and remove the macro and the constructors from AnotherPileOfData. There would be only one constructor to keep in a certain format and that’s the one taking the blob. I’d probably turn it into a static builder function or a free function as it was suggested by Jonathan Boccara on FluentC++.

123
AnotherPileOfData makeAnotherPileOfData(const Blob& blob) { return AnotherPileOfData{blob.label, blob.text, blob.quantity};}

Conclusion

In my opinion, a struct barely needs a constructor. With the combination of aggregate initialization, designated initializers and the right order of members, you can easily get rid of constructors in a struct. In those rare cases, when you’d still need them you can replace it with a free function keeping your struct as simple as possible.

At the same time, it’s worth noting that sometimes a struct has constructors and special member functions to limit binary sizes. By moving special member functions to implementation files, we can limit inlining and thus decrease binary sizes.

Connect deeper

If you liked this article, please

Structs and constructors (1)

Structs and constructors (2024)

FAQs

Structs and constructors? ›

A struct is created by calling a constructor function using the new operator, by creating a struct literal {} or returned by some function. An instance, on the other hand, is created from an object using instance_create_depth or instance_create_layer. Structs are just variables and don't have events.

What is the difference between a constructor and a struct? ›

A structure called Struct allows us to create a group of variables consisting of mixed data types into a single unit. In the same way, a constructor is a special method, which is automatically called when an object is declared for the class, in an object-oriented programming language.

Can a struct have multiple constructors? ›

A class or struct may have multiple constructors that take different arguments.

Do structs need constructors C#? ›

If a struct declares any field initializers, it must explicitly declare a constructor. That constructor need not be parameterless.

What is the difference between a struct and a class method? ›

Use structs for small, lightweight objects that represent simple data types, such as coordinates, colours, or key-value pairs. Use classes for more complex objects that require behaviour, encapsulation, and inheritance, such as entities in an object-oriented design.

Does a C++ struct need a constructor? ›

Technically, a struct is like a class , so technically a struct would naturally benefit from having constructors and methods, like a class does.

How to create a constructor in a struct? ›

To create a parameterized constructor for a struct, you simply define a constructor method with the public access modifier and one or more parameters. Make sure to assign the values of the parameters to the corresponding fields of the struct.

Can a struct have a copy constructor? ›

A copy constructor is generated implicitly by the compiler for a struct S if all of the following conditions are met: S does not explicitly declare any copy constructors; S defines at least one direct member that has a copy constructor, and that member is not overlapped (by means of union) with any other member.

Can one class have two constructors? ›

A class can have multiple constructors, as long as their signature (the parameters they take) are not the same. You can define as many constructors as you need. When a Java class contains multiple constructors, we say that the constructor is overloaded (comes in multiple versions).

Why can't structs inherit from another struct? ›

Because it is the way structs are represented in . NET. They are value types and value types don't have a method table pointer allowing inheritance.

When should I use structs? ›

Structs are best used when you need to represent simple data types, such as integers, strings, or other basic data types. They are also useful when you need to work with large datasets, such as arrays or lists, where performance is critical.

Can a struct be null? ›

Furthermore, except when explicitly nullable (§8.3. 12), it is not possible for values of a struct type to be null .

What is the point of structs in C? ›

Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, float, char, etc.).

Is struct faster than class? ›

However, the same differences between structs and classes are still present: structs are significantly faster than classes.

Why choose struct over class? ›

There are, however, some situations in which the characteristics of a value type make it more appropriate to use structs. ✔️ CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.

Can we create an object of a struct in C#? ›

When you create a struct object using the new operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator.

What is the difference between const and struct? ›

The const part really applies to the variable, not the structure itself. It means the struct is constant i.e. you can't edit it's fields after it's been initialized. 'const' as the word constant itself indicates means unmodifiable. This can be applied to variable of any data type.

What is the main difference between constructor and method? ›

What is the main difference between a Constructor and a Method? A constructor helps in initializing an object, has no return type and cannot be inherited by subclasses. On the other hand, a method executes operations, returns a value, and can be inherited by subclasses.

What is the difference between constructor and builder? ›

The constructor constructs the object you need, while the builder is a helper object to construct what you need.

What does struct mean in construct? ›

Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, float, char, etc.).

Top Articles
Healthy Easy To Make Low Calorie Recipes | LaaLoosh
Air Fryer Recipes for Beginners
Spasa Parish
Rentals for rent in Maastricht
159R Bus Schedule Pdf
Sallisaw Bin Store
Black Adam Showtimes Near Maya Cinemas Delano
Espn Transfer Portal Basketball
Pollen Levels Richmond
11 Best Sites Like The Chive For Funny Pictures and Memes
Xenia Canary Dragon Age Origins
Momokun Leaked Controversy - Champion Magazine - Online Magazine
Maine Coon Craigslist
‘An affront to the memories of British sailors’: the lies that sank Hollywood’s sub thriller U-571
Tyreek Hill admits some regrets but calls for officer who restrained him to be fired | CNN
Haverhill, MA Obituaries | Driscoll Funeral Home and Cremation Service
Rogers Breece Obituaries
Ems Isd Skyward Family Access
Elektrische Arbeit W (Kilowattstunden kWh Strompreis Berechnen Berechnung)
Omni Id Portal Waconia
Kellifans.com
Banned in NYC: Airbnb One Year Later
Four-Legged Friday: Meet Tuscaloosa's Adoptable All-Stars Cub & Pickle
Model Center Jasmin
Ice Dodo Unblocked 76
Is Slatt Offensive
Labcorp Locations Near Me
Storm Prediction Center Convective Outlook
Experience the Convenience of Po Box 790010 St Louis Mo
Fungal Symbiote Terraria
modelo julia - PLAYBOARD
Poker News Views Gossip
Abby's Caribbean Cafe
Joanna Gaines Reveals Who Bought the 'Fixer Upper' Lake House and Her Favorite Features of the Milestone Project
Tri-State Dog Racing Results
Navy Qrs Supervisor Answers
Trade Chart Dave Richard
Lincoln Financial Field Section 110
Free Stuff Craigslist Roanoke Va
Stellaris Resolution
Wi Dept Of Regulation & Licensing
Pick N Pull Near Me [Locator Map + Guide + FAQ]
Crystal Westbrooks Nipple
Ice Hockey Dboard
Über 60 Prozent Rabatt auf E-Bikes: Aldi reduziert sämtliche Pedelecs stark im Preis - nur noch für kurze Zeit
Wie blocke ich einen Bot aus Boardman/USA - sellerforum.de
Infinity Pool Showtimes Near Maya Cinemas Bakersfield
Dermpathdiagnostics Com Pay Invoice
How To Use Price Chopper Points At Quiktrip
Maria Butina Bikini
Busted Newspaper Zapata Tx
Latest Posts
Article information

Author: Horacio Brakus JD

Last Updated:

Views: 6556

Rating: 4 / 5 (71 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Horacio Brakus JD

Birthday: 1999-08-21

Address: Apt. 524 43384 Minnie Prairie, South Edda, MA 62804

Phone: +5931039998219

Job: Sales Strategist

Hobby: Sculling, Kitesurfing, Orienteering, Painting, Computer programming, Creative writing, Scuba diving

Introduction: My name is Horacio Brakus JD, I am a lively, splendid, jolly, vivacious, vast, cheerful, agreeable person who loves writing and wants to share my knowledge and understanding with you.