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 astruct
?
相关问题
- how to define constructor for Python's new Nam
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Keeping track of variable instances
- Why does const allow implicit conversion of refere
相关文章
- 接口B继承接口A,但是又不添加新的方法。这样有什么意义吗?
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
as others have explained, they're the same thing except for default access levels.
the only reason why classes can be perceived to be slower is because a good style (but not the only one) is the one mentioned by ArmenTsirunyan:
struct
for POD types,class
for full-fledged object classes. The latter ones usually include inheritance and virtual methods, hence vtables, which are slightly slower to call than straight functions.I like to use classes when I need to have an explicit destructor. Because then, you should be following the rule of three, in which case you need to write a copy constructer and assignment overloader. With all of this, it seems more natural to use a class than a struct.
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
1) There is no real difference between the 2 other than the fact that struct members are, by default, public where classes are private.
2) No its EXACTLY the same.
Edit: Bear in mind you can use virtual inheritance with structs. They are THAT identical :)
Instead of cheaping out and referring to other questions, I'll re-iterate what others have said before I add on to them.
struct
andclass
are identical in C++, the only exception being thatstruct
has a default access ofpublic
, andclass
has a default access of private. Performance and language feature support are identical.Idiomatically, though,
struct
is mostly used for "dumb" classes (plain-old-data).class
is used more to embody a true class.In addition, I've also used
struct
for locally defined function objects, such as: