The difference between Structure and Class in C++

It’s a common question asked, especially in job interviews and college exams, the question of what is the difference between Structure and Class in C++. Both concepts seem similar but if you go into detail, Structs and Classes are actually two different things. In C++, a struct is similar to a class except with the following differences:

  1. Since structs originally came from the C language, which are declared using “struct”, the same principle applies as a group of data elements are grouped together under one name.  The members of the struct are public by default. With a class, members of the class are private by default.
  2. Since classes are private by default, classes have the advantage of setting the members of the class to either public, protected or private.
  3. If you are deriving a struct from a class, default access for a base class/struct is public. When you are deriving a class, the default access is private.

To take advantage of the power of C++ of writing object orientated programs, you will need to use classes. An analogy to understand what classes do is that they are known as a blueprint of what is going to be implemented in a program. The code examples of writing a class and a struct are shown below. Both of them look the same but there needs to be a fundamental understanding with the two concepts.

Example Struct code

</pre>
<pre>struct groceries

{

// members of the struct

string name;

int weight;

double price;

} chips, drinks; // Objects of the struct
</pre>
<pre>

Example class code

</pre>
<pre>//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−

// Example of a class declaration in C++

//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−

class Groceries

{

// Members of the class

string name;

int weight;

double price;

int total();

};
</pre>
<pre>
Share this post