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

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"?

Related

Significance of classes over data-structures

Whats the significance of classes over data-structures or data-structures over classes?
Ok so The most basic ones can be that we can use "Access Specifiers In Classes" meaning we can prevent some and allow some to access our data.
next can be that data-hiding.
But whats the main thing that separates classes and data-structures? I mean why need data-structures when we have classes or vice-versa?
C++ has fundamantal types, and classes.
Struct and Class are both keywords that introduce a new class. There are slightly different defaults.
Data structures are an arrangement of data with some kind of invarient. They can be a class, they can contain classes, or they could be completely class free.
They are different categories of thing. It is like asking what the difference is between steel and an automobile.
In a course assignment, what the teacher is asking for is for you to know the definition the teacher or the text taught those terms meant. Terms mean what the context they are in tells them to mean. It is a matter of "are you paying attention" not "do you know this fact"; having asked it of the internet, you have already failed.
In terms of syntax, in C++ the only difference between a class and a struct is that members of a struct are public by default, while the members of a class are private by default.
From a perspective of implied design intent, however, there is a larger difference. struct was/is a feature of C, and was/is used (in both C and C++) to help the programmer organize Plain Old Data in useful ways. (for example, if you know every Person in your persons-database needs to store the person's first name, last name, and age, then you can put two char arrays and and int together in a struct Person and thereby make it more convenient to track all of that data as a unit, than if you had to store each of those fields separately).
C++ continues to provide that C-style struct functionality, but then goes further by adding additional features to better support object-oriented-programming. In particular, C++ adds explicit support for encapsulation (via the private and protected keywords), functionality-extension via inheritance, the explicit tying-together of code and data via methods, and run-time polymorphism via virtual methods. Note that all of these features can be approximated in C by manually following certain coding conventions, but by explicitly supporting them as part of the language, C++ makes them easier to use correctly and consistently.
Having done that, C++ then goes on to muddy the waters a bit, by making all of that new functionality available to structs as well as classes. (This is why the technical difference is so minor, as described in the first paragraph) However, I believe it is the case that when most programmers see a struct defined, they tend to have an implicit expectation that the struct is intended be used as a simple C-style data-storage/data-organization receptacle, whereas when they see a class, they expect it to include not just "some raw data" but also some associated business-logic, as implemented in the class's methods, and that the class will enforce its particular rules/invariants by requiring the calling code to call those methods, rather than allowing the calling code to read/write the class's member-variables directly. (That's why public member-variables are discouraged in a class, but less so in a struct -- because a public member-variable in a class-object contradicts this expectation, and violates the principle of least surprise).

Is it possible in C++ to make an instance of a class as a member of structure? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
struct Frame {
int frame_num;
BoundingBox bbox;
};
In this above structure, BoundingBox is a class and later used in the following way. What is the benefit of making a class instance as a member of a structure?
Is it possible in C++ to make an instance of a class as a member of structure?
You've answered your own question in your snippet. Yes, possible.
what is the benefit of making a class instance as a member of a structure?
What is the benefit of int frame_num in Frame? It's the same benefit you get in having custom types.
Classes are a way of making custom types (BoundingBox in your example) which work besides the built-in types (int, float, etc.) the language gives out of the box. Both can be put inside another custom type (like Frame) and they provide a way to interact with data. E.g. int is a type that allows the programmer to work with integer data in a specified way i.e. int dictates how the values of its type interact with say float. Likewise, a custom type will allow the user of the type to work with some data is some fashion.
Aside: Classes and structs are almost the same in C++.
It's perfectly fine. Go ahead and use it.
The two abstractions -- Frame and BoundingBox -- server their own purposes. Whether one is a class and the other is a struct does not change that.
In essence, structures are almost identical to classes.
However, members of a struct are declared as public by default, while members of a class are declared as private ones.
Why not? A struct is a class so there is nothing special about them.
It's called "Object Association", and it depends on the design. Typically, object association is called the "Has-A" relationship.
In C++ Class and Struct are the Same thing, with minor difference of the default access modifier being private for class and public for structs
Additionally, syntax speaking nesting those constructs is allowed if not required inorder to get correct OOP design.
That said, I'd note that, semantically, there is a difference:
as structs are mostly used to describe data,
while classes mostly describe object.
Some programmers might (allow themselves to) use memset on a struct, or copy it to another memory location.
These operations might corrupt the class like struct by:
- corrupting vptr of the contained class member
- If this struct has a virtual method itself then it's own vptr.
- Copy pointers and create some surprising results.
Bottom Line:
Nest classes in classes, structs in classes...
But avoid nesting class in struct, there is no good reason to do so.
Also, You might want to embrace the convention of "struct -> DATA, class -> Object"

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.

Public variables bad practice vs Getters and Setters functions? [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 7 years ago.
Improve this question
I came across this during his stream, and this stuck out to me like a sore thumb since. I thought maybe if I saved the video and come back to it in the future when I'm more proficient I'll understand it, but it just kept on bothering to just leave it be. Here's the video...
It automatically starts at 1:13:00 for you.
https://youtu.be/uHSLHvWFkto?t=4380
As a new programmer to C/C++ after hearing this its completely warped my way of thinking. With him being a professional and all I should take the advice, but I need some clarity. From sites, videos, to books, I've read that the use of public variables is a bad practice, but from what I'm getting from this video its saying otherwise. In the video he's uses a struct which by default has a access modifier of "public" vs a class which has a default access of "private". Is there something I'm not comprehending properly here.
I don't know what to do. If I make my variables public won't I risk ambiguity ? The way he's saying that he'll automatically fire someone for coding in format is getting to me haha! Which one should I truly use ? When and Why ?
In my experience people use getters/setters excessively for no good reason.
One can think of two major kinds of classes: the ones grouping together related data and the others providing behaviour.
Behaviour classes must be encapsulated with no public data members.
Data classes normally should have data members public and no behavior.
The grey area between these two is mutable data classes with invariants or dependencies between members, e.g. if member a is 1, then member b must be in range [1-10]. For such cases usage of getters/setters may be justified. For immutable data classes the constructor must establish the invariant.
First of all, a struct is completely equivalent to a class, but with the default member access being public rather than private.
Now, in Object Oriented Programming (OOP), it's not considered good practice to have public data members (variables), because that makes all your code dependent on the internals of the class, and thus breaking a primordial principle of OOP, and that is...
Holy and Sacred Encapsulation
Encapsulation is the coding philosophy that states that a class should englobe both data and the code that manages it in a single tight entity. That is, you don't access data directy, but rather you use methods from the class to manipulate such data. This has several design advantages, such as that you'll know that no code except the one inside the class may incorporate bugs with respect to the manipulation of such information.
Now, get()ers and set()ers, otherwise known as accessors, are a complete lie! With accessors, you're tricking yourself into thinking that you're respecting encapsulation, when you're rather breaking it! It adds bloat, unnecessary verbosity, bugs, and everything but encapsulation. Instead of having a class Person with unsigned getAge() and void setAge(unsigned), have it with a unsigned getAge() and a void incrementAge() or however you want to call it.
Now, to your question's core...
"Plain old" structs
Encapsulation is not always desired. Although you should (usually) not do this on header files (again, for at least some bit of encapsulation), you may create static plain old structs that are private to a single translation unit. My recommendation is to make them even "older" than they already are, i.e...
All data members are public.
No methods.
No constructors (except implicit ones).
Inheritance is always public, and only allowed from other plain old structs.
I repeat, don't put them on header files!
Now, another use for plain old structs is (ironically) metaprogrammatic exporting of constexpr data and types, otherwise known as modern-hardcore-template-metaprogramming-without-having-to-type-public-everywhere, for example...
template<bool B, typename T>
struct EnableIf {};
template<typename T>
struct EnableIf<true, T> {
typedef T type;
};
template<bool B, typename T>
using SFINAE = typename EnableIf<B, T>::Type;
It's certainly difficult to control the internal consistency of your object if you make the data members public.
What works well is to use constructors to set up the state of an object, then use public functions to retrieve values of member variables, but only if that's needed. If you need to mutate the object after construction, then provide very specific methods for that purpose.
If, however, your object is no more than something that aggregates orthogonal data types, then use public access for all members: a struct works well for that.
Note that the only difference between a struct and a class is that in the former, the default access is public whereas in the latter it is private.
If you keep your data members private then you can easily control about accessing their value. For example you have age variable in your code.
public:
int age;
Now someone outside your class can easily change value of age, may also assign illegal value, for example age = -10. But your logic suggests age cannot be negative, so best practice is to keep variable private, and give some function which will assign value to your variable.
private:
int age;
public:
void setAge(int age)
{
if (age > 0)
this->age = age;
}

Structs vs classes in C++ [duplicate]

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.