Structs vs classes in C++ [duplicate] - c++

This question already has answers here:
Closed 14 years ago.
When should someone use structs instead of classes or vice versa in C++? I find myself using structs when a full-blown class managing some information seems like overkill but want to indicate the information being contained are all related. I was wondering what are some good guidelines to be able to tell when one is more appropriate than the other?
Edit:
Found these links while reading the material Stack Overflow indicated was related after the question was submitted:
When should you use a class vs a struct in C++?
What are the differences between struct and class in C++?

Technically, the only difference between the two is that structs are public: by default and classes are private:
Other than that, there is no technical difference.
struct vs class then becomes a purely expressive nuance of the language.
Usually, you avoid putting complicated methods in a struct, and most of the time structs data members will stay public. In a class you want to enforce strong encapsulation.
struct = data is public, with very simple helper methods
class = strongly encapsulated, data is modified / accessed only through methods

I use structs for simple containers of types that provide no constructors or operators.
Classes for everything else.

Use a struct when you simply need a "bucket of stuff" that doesn't have logical invariants that you need to keep. Use a class for anything else.
See also what the C++ FAQ says on the subject.

Use a class if you have methods, a struct if not.
A class should hide all its internals only exposing methods or properties. A struct tends to expose all its internals and has no accessor methods.
Where only one bit of code is accessing some (related) data, a struct may be perfectly reasonable. Where multiple bits of code need to modify the data or if it's anything slightly complicated, a class would be a better bet.

The difference between Classes and Structs are that structs are groups of variables and classes represent objects. Objects have attributes AND methods and be part of a hierarchy.
If you're using C++ to take advantage of the OO capabilities it's best to use classes / objects which are more natural.

I always use class, even for just containers, for consistency. Its purely a choice of style since the difference between the two is negligible.

If you need to control access to the data, you should use classes. If you don't care who is accessing what, and what they're storing in there, then a struct is probably more appropriate.
Also, a class is more appropriate if you need to do any checks on the integrity of the data itself.

See existing questions:
What are the differences between struct and class in C++
When should you use a class vs a struct in C++?

Personally, I use structs when all I need is a container for data (no member functions).
Otherwise, I use classes.
The only time I make an exception to that rule is if I need a simple functor: e.g.
struct compare { bool operator() { ... } };
sort(v.begin(), v.end(), compare());
The need for a public: label would just clutter up the code unnecessarity.

structs in C++ are classes with a default access method of public, so technically other than that default there is no difference and you can use both equivalently.
Yet there are some expectations and natural tendencies, in part because structs in C++ come from C.
My approach: If it has any private data, a constructor/destructor, or any complex member functions (which do more than just conversion upon set/get, etc.), use class.

Related

C++ struct inheritance [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
As far as I know the main difference (and may be the unique one) between classes and structs in C++ is that classes have their members private by default and structs have theirs public by default.
However, and probably because I was a C-developer before, I still continue to declare structs to hold only "public" fields, and I almost never declare methods (except constructors to initialize members).
I also want to take advantage of C++ inheritance for structs.
My questions are:
Even if the language allows it, is it a good practice to inherits structs ?
Is it possible to prevent a struct to declare a virtual method, which will create a vtable and modify the size of the struct ?
Thank you
classes have their members private by default and structs have theirs public by default.
Structs also inherit public by default, where classes inherit private by default.
Even if the language allows it, is it a good practice to inherits structs ?
Sure. It works exactly as you would expect.
Is it possible to prevent a struct to declare a virtual method, which will create a vtable and modify the size of the struct ?
Not yet. There is a proposal for C++20+ (P0707) to allow exactly this, but it's still pretty young and not implemented far enough to be used anywhere. In particular, search for "3.6 plain_struct" to see how they enforce plain structs to be that.
In general I would recommend using a struct when you're using it as a "struct" sort of function - holding data without invariants. If you have invariants, you should keep them using encapsulation and data hiding, so it should be a class.
Just want to address this question:
Even if the language allows it, is it a good practice to inherits structs ?
You should rid yourself of connotation that "struct" indicates POD. Sometimes, the most reusable components are those that don't encapsulate anything, despite having some behavior.
For instance, consider this meta-function:
template<typename T> struct is_foo : std::false_type {};
template<> struct is_foo<Foo> : std::true_type {};
All of the above types (and the types behind the aliases for true and false) are declared with the struct keyword. This is simply because having everything public by default forwards the behavior we want without us having to spell it out every time.
Another time when you find yourself inheriting from a "struct" is when extending a C library. If the library defines a structure named struct Bar that is used to communicate with it, the easiest way you can add functionality to it, is by inheriting from Bar. Like this:
class ExtendedBar : Bar {
void mem_func() {
//Need to call the C library function? No problem
c_library_func(this); // ExtendedBar is-a Bar
}
};
The only important difference is the default accessibility levels. And the only thing you should concern yourself with (IMO) is which default accessibility works best for your purpose.
Even if the language allows it, is it a good practice to inherits structs?
Yes it is. Just look around C++ STL (Standard Template Libraries). You will find struct in abundance.
Is it possible to prevent a struct to declare a virtual method, which will create a vtable and modify the size of the struct ?
No.... as of now.. As soon as you declare virtual functions.. the vtable will be created for struct
Structs vs Classes
You are correct, a primary difference between struct and class in C++ is default access levels. Without an explicit access modifier, class members are private, and struct members public. Struct members can also be made private using an access modifier. Keep in mind; this also applies to inherited classes and structs.
As for a general recommendation: many use structs only for data and classes for everything with behavior [1]. In other words, structs for POD (Plain Old Data) types[2], this is a widespread practice. It does not mean you cannot have functionality related to accessing and setting data members, setting up constructors, destructors, etc. "If more functionality is required, a class is more appropriate. If in doubt, make it a class." Their guide also recommends structs instead of classes for functors and traits.
You have to keep in mind, aside from any technical upsides or downsides, there are other reasons to enforce specific practices and standards in a team, and on a project basis. As also mentioned in Google's style guide, we can add semantic meaning to the data structures we use. As a team member, I would want to know if structs have behavior or not. It would be nice to know, for instance, that all structs are just POD types.
The Joint Strike Fighter coding standard specifies, "A structure should be used to model an entity that does not require an invariant." While "A class should be used to model an entity that maintains an invariant." And that public and protected data should only be used in structs, not in classes. Their rationale for this is that a class can't control access to public members; hence, all data in a class should be private. Consider the needs of your project when deciding on coding standards.
Struct inheritance
When thinking about inheritance, you must consider what public inheritance means versus private inheritance. Keep in mind what access levels the new, derived one will have, and if it makes sense to inherit your structs. Struct members can be made private, if you inherit from this, the derived one will not have access to the base's private members.
struct base {
int public_data;
private:
int private_data;
};
struct derived : base {
derived() {
public_data = 1;
// private_data = 1; // no access, won't compile
}
};
In other words, inheritance might be considered more of a logical issue than an implementation one.
There is nothing, technically, fundamentally wrong with inheriting structs. It might be a benevolent practice, and it might, in some cases, be beneficial and make a lot of sense.
Keep in mind, in C++, structs can inherit from classes and vice versa.
See this question for more information on vtables: When is a vtable created in C++?
[1] https://google.github.io/styleguide/cppguide.html#Structs_vs._Classes
[2] http://en.cppreference.com/w/cpp/concept/PODType
As far as I know the main difference (and may be the unique one) between classes and structs in C++ is that classes have their members private by default and structs have theirs public by default.
The only difference between classes declared with the keyword struct, and those declared with the keyword class is indeed the default access specifier (which applies to bases too as well as members).
Indeed, the easiest way to understand structs is to understand that they are classes.
Even if the language allows it, is it a good practice to inherits structs ?
Sure. It is OK to inherit a class, and structs are classes.
Is it possible to prevent a struct to declare a virtual method, which will create a vtable and modify the size of the struct ?
No, there is no such feature as far as I know.
Given struct A { ... };, struct B { A a; ... } is much safer than struct B : A { ... }.
I suggest not inheriting is better than inheriting with non-virtual destructor. The only thing you lose is the implicit conversion from B*, B& to A*, A& etc. However you still have the explicit B b; b.a for those circumstances.

Why do we need a `class` in C++, when a `struct` can be used to achieve the same? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Using a struct we can achieve all the functionality of a class: constructors (that can be modified/overloaded), destructors (that can be modified/overloaded), operator overloading, instance methods, static methods, public/private/protected fields/methods.
Why do we need class then?
Note: I don't want the answer saying that in struct, fields/methods are public by default.
You don't need classes, the language just gives you another option to choose from. Technically, you're right, you can achieve anything a class can do with a struct.
Besides the default access level, there's also the meaning most programmers associate with the two - struct generally means a light-weight, typically POD, data-type with little to no functionality. A class is usually associated with something bigger.
As Tal Pressman answered at When should you use a class vs a struct in C++?:
From the C++ FAQ:
The members and base classes of a struct are public by default, while in class, they default to private. Note: you should make your base classes explicitly public, private, or protected, rather than relying on the defaults.
struct and class are otherwise functionally equivalent.
OK, enough of that squeaky clean techno talk. Emotionally, most developers make a strong distinction between a class and a struct. A struct simply feels like an open pile of bits with very little in the way of encapsulation or functionality. A class feels like a living and responsible member of society with intelligent services, a strong encapsulation barrier, and a well defined interface. Since that's the connotation most people already have, you should probably use the struct keyword if you have a class that has very few methods and has public data (such things do exist in well designed systems!), but otherwise you should probably use the class keyword.
http://www.parashift.com/c++-faq-lite/classes-and-objects.html#faq-7.8
I think one addition to this reason could be that C already had structs. When Bjarne Stroustrup designed C++, he wanted to add classes with all the functionalities you listed in your original question, features which were not present in C. When implementing those features, he probably realised it didn't make sense to make two separate implementations for struct and class (except the public/private default visibility).
TL/DR: in C++ structs/classes describe the intent of the programmer to have POD or more complex abstractions, and the introduction of the class keyword is probably here for historical reasons (add an additional keyword in order to create featurefull classes, then backport those features into the struct keyword because it's more pragmatic to implement).
class is simply the commonly accepted name in OO for a type used for instantiating objects. When introducing the OO paradigm in C++, it was deemed less surprising to use class instead of struct.
struct was kept to maximize backwards compatibility with C.
Today's usage of the two is in line with this : struct is most commonly used for C-style POD types, while class is used for the OO concept of classes.
To make a long story short, class really wasn't needed at all. It changes the defaults to ones that are arguably safer and more applicable to OO programming, but you could use a struct (as defined by C++) for any place that you currently use a class (if you wanted to get cute and meta about it, you could call struct a base class of class that satisfies the LSP).
At the same time, misunderstanding of struct in C++ is rampant, and class fits the intended concept enough better that it's often much easier to explain. New users often seem to find it at least marginally more understandable -- a reasonable goal in itself.
There are no such difference between C++ struct and C++ class, you can perform almost all the functions with struct as you can do with class, but struct is a C keyword which gradually got modified/evolved in C++ and named as class. A we are in C++, it is better to use class rather than struct.
Take an example, if you have done some coding in C++ and some person who works in Java came after 2 months to review your code, which one will he find comfortable to understand a code with "struct" or a code with "class"?

Class in a struct

I have two questions.
I know it is possible to declare class objects in structs. But is it ethical to do that from design point of view?
In my scenario I have a structure with a huge number of member elements and I want to include a class object too. Here I have another question. If I memset() the whole struct the class handle is also reset. So, I check the size of the rest of the struct without the class object and subtract it while I call memset(), to get rid of this problem. (Please note that I am using STL class 'queue' here. And I cannot use sizeof() operator on the object, since it is not overloaded.)
But is this totally an unacceptable way to do that? Can you suggest some solution to this problem?
struct = class (except for default visibility).
If you have a “huge number of members” you are probably doing something wrong, change your design, otherwise it becomes intractable.
It is absolutely fine to nest classes and / or structs, where it makes sense. For instance, it’s common to define nested classes for implementation details (so a linked_list class could have a node member class).
There’s no such thing as a “class object”, and it’s not clear what you mean by that.
Don’t use memset – you probably don’t need it, just use normal constructors and assignment.
And I cannot use sizeof() operator on the object
Wrong, you can use it.
The solution is to avoid memset with classes and structures, and use constructors. In C++11 you can use initialization lists too under various conditions.
There is no much functional difference between classes and structs in c++. Structs exisist in c++ only for backward compatibility with C. So it is ok to have a class objects in structs. However I generally prefer structs that have only member variables with getter and setter. I dont use any functions inside struct that manupulate the data. If i need that then i will use class.

C++: making custom class to work like both container and normal class?

I want to have some myObject which will store a collection (vector-like) of SomeOtherObjects (so, being homogeneous, right?), which should be iterable and accessible via (myObject[i]).SomeOtherObjectField1 but also will have normal members like myObject.doStuff() and myObject.Stuff.
Is there any option to implement such class, or using private std::vector to keep the objects (which I'm trying to avoid - don't like private std:: containers) will be smarter?
Prefer composition over inheritance, if your goal is code reuse. (Inheritance should be used to enable polymorphism, which doesn't seem to be an issue in this case.)
That's looks like the composite design pattern. In short, you have to define the interface of your Object class and derive concrete classes, some being container for others. As said, the composition way is better, but using a common interface is the way to use a 'simple' Object or a 'composite' Object the same way.
my2c
I would use a private std::vector<> and an inline method to return a const reference to it.
Why don't you like member std containers?
Often the right approach to structure lies in clarifying the semantics. You need to ask questions like
"Is myObject a vector<>?". The answer is probably not. If you then follow the principle that a class does one thing (cohesion), then it follows that syntactic sugar around the vector<> is probably not that good.
It tends to follow that the vector<> is a private member. There is no problem with then returning a const reference to it. Returning a non-const reference would break encapulsation - might as well be public data.
If you wish to have:
(myObject[i]).SomeOtherObjectMethod1();
then that is easy enough to implement through operator[](unsigned index). I suspect if you do want that you are better off being consistent and treating myObject as a container in its own right. This means not providing the const ref accessor to the vector<> and implementing the specific accessor methods you really require. This will make client code much easier to understand.

Why would I use a struct in a program?

I see lot of struct code like below
struct codDrives {
WCHAR letter;
WCHAR volume[100];
} Drives[26];
We can use variables or array something like that to store the data.
But I am not sure why would I use a struct in the programs?
Structs are inherited from C, and in C++ they are almost identical to classes. The difference is that the members of a struct are by default public, while class members are by default private.
So the typical use of structs in C++ is dummy data structures which contain no logic (only - possibly - constructors and/or necessary operators).
On a more general level, classes / structs are used to group together conceptionally related data pieces. E.g. for representing a person, you may need his/her first name, surname, gender, date of birth etc. It is convenient to define a struct containing all these pieces of data as members. Then you can store and pass around instances of this struct instead of a whole bunch of distinct variables. This makes the code cleaner, less error prone, more readable and easier to maintain.
Here's some info on structs:
http://www.cplusplus.com/doc/tutorial/structures/
Also, they are useful for example returning multiple values in a function, say you need to return 3 values from a function, you can return a struct with all the 3 values inside it.
One reason to use structs might be to control the size and layout of the data so it can be written to and read from disk more easily.
Another reason would be for code that is used in C programs as well as C++
Structs can also contain methods (constructors are very useful for example). Another thing is, that with structs or classes you can define copy constructors or assignment operators which then allow you to easily copy instances of your struct, even if there are pointers inside - you take care of this in the methods of the struct and don't have to worry about it later. Moreover, this allows for a nice OOP design. There are much more benefits (but also drawbacks)...