Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: When should I use structs instead of classes and where are the speed differences?

Tags:

  • When should I use a struct instead of a class? I'm currently using classes for everything from OpenGL texture wrappers to bitmap fonts.

  • Is a class that I use just like a struct (no making usage of inheritance, polymorphism, etc.) still slower than a struct?

like image 252
Markus P. Avatar asked Nov 03 '10 19:11

Markus P.


People also ask

When should a struct be used instead of class?

In classes, two variables can contain the reference of the same object and any operation on one variable can affect another variable. In this way, struct should be used only when you are sure that, It logically represents a single value, like primitive types (int, double, etc.). It is immutable.

Are structs faster than classes?

So based on the above theory we can say that Struct is faster than Class because: To store class, Apple first finds memory in Heap, then maintain the extra field for RETAIN count. Also, store reference of Heap into Stack. So when it comes to access part, it has to process stack and heap.

Are structs faster?

Unlike class, struct is created on stack. So, it is faster to instantiate (and destroy) a struct than a class.

When should a struct be used?

Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created. 5) A struct is a value type. If you assign a struct to a new variable, the new variable will contain a copy of the original.


1 Answers

Structs and classes in C++ as you may know differ solely by their default access level (and default accessibility of their bases: public for struct, private for class).

Some developers, including myself prefer to use structs for POD-types, that is, with C-style structs, with no virtual functions, bases etc. Structs should not have behavior - they are just a comglomerate of data put into one object.

But that is naturally a matter of style, and obviously neither is slower

like image 166
Armen Tsirunyan Avatar answered Jan 21 '23 00:01

Armen Tsirunyan