Ask a Teacher



What is the difference between class and structure?

The struct default access type is public. A struct should typically be used for grouping data. 

The class default access type is private, and the default mode for inheritance is private. A class should be used for grouping data and methods that operate on that data. 

In short, the convention is to use struct when the purpose is to group data, and use classes when we require data abstraction and, perhaps inheritance. 

In C++ structures and classes are passed by value, unless explicitly de-referenced. In other languages classes and structures may have distinct semantics - ie. objects (instances of classes) may be passed by reference and structures may be passed by value.
Technically there are only two differences between classes and structures: 

classes are declared using the keyword class while structures are declared using the keyword struct
structures are entirely public, while classes are private by default

Most C++ programmers use structures exclusively for data that doesn't require strict validation while classes are used to encapsulate data and the functions that work exclusively with that data. Although classes and structures can largely achieve the same goals, the lack of encapsulation and data-hiding in a structure make it far less robust than a well-designed class would be, with little or no difference in terms of memory consumption. Encapsulation comes into its own when classes become highly-complex (classes within classes) as each class is responsible only for its own data, not the classes it contains. Structures can be just as complex, but because they don't have the safeguards that can built into classes, it only takes one errant function to unwittingly invalidate data. A well-designed class ensures data validity at all times.


comments powered by Disqus