What is real difference between Class and Structure when you are dealing with Object Oriented Programming. This question is asked many times during my interviews for SE.
Some people says that there is only one difference:
Structure members are public by default and Class members are private by default.
Some says there are many differences.
After reading many articles and forums, I have the following differences:
Classes DEFAULT to having private members. Structures DEFAULT to having public members.
Structures are values type.
Classes are reference type.
Structure stores in memory via stack.
Classes stored in memory via heap.
Structure doesn’t support inheritance.
Classes support inheritance.
Constructor works in different way.
‘new’ operator works in different way.
Allocating memory for structure is very fast because this takes place inline or on the stack.
What are your opinion on my above list or you have a different one. Thanks
This is pretty language-specific. You seem to be mixing a fair share of both C++ and C#, both of which are very different languages (despite superficial similarities in syntax).
In C++
structs indeed default topublicmember visibility whileclassdefaults toprivate. In C#structis used to declare value types which are passed by value (note that the stack allocation is an implementation detail, not a contract).Generally both languages seem to have the same idea of what
structandclassshould represent:structis for simple data structures which do little more than holding data, while classes have state and methods to manipulate it. They are used to build objects in some concrete or abstract sense while data structures are just that: data in a structured form; they don’t need to do much with that data or even know what data that is. Essentially they’re dumb and don’t care.But that’s just how the language designers thought they should be used. People are good at mis-using things so not every
structyou see may be a simple, dumb data structure and not everyclassyou see may be a full-blown class with lots of methods and whatnot. It’s merely a convention and if people follow it others can look at the code and see “Oh, nice, that’s astructso I don’t expect much logic here and move on to more interesting things.” It might work … in theory.ETA: Since you mentioned in a comment that you are particularly interested in PHP or Java: Both languages do not have any distinction at the syntax or language level of
classorstructwhich is why your question strikes me as a little odd. In both Java and PHP you model things as classes, regardless of whether they are just data structures without logic or actual classes with everything there is.