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
?
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.
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.
Unlike class, struct is created on stack. So, it is faster to instantiate (and destroy) a struct than a class.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With