Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

What are the differences between struct and class in C++?

Presently I'd prefer to get familiar with the contrasts between a struct and a class in C++. Kindly talk about the technical differences just as explanations behind picking either in OO plan.

I'll begin with an undeniable distinction:

On the off chance that you don't indicate public: or private:, individuals from a struct are public as a matter of course; individuals from a class are private naturally.

I'm certain there are different contrasts to be found in the dark corners of the C++ particular.
by

3 Answers

espadacoder11
The only other difference is the default inheritance of classes and structs, which, unsurprisingly, is private and public respectively.
sandhya6gczb
The difference between class and struct in C++ is

Members of a class defined with the keyword class are private by default. Members of a class defined with the keywords struct or union are public by default.

The keyword class can be used to declare template parameters, while the struct keyword cannot be so used.
pankajshivnani123
Quoting The C++ FAQ,

[7.8] What's the difference between the keywords struct and class?

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.

Login / Signup to Answer the Question.