It’s a common question asked, especially in job interviews and college exams, the question of struct vs class in C++. Both concepts seem similar but if you go into detail, struct vs class is actually two different things. In C++, a struct is similar to a class except for the following differences:

  1. Since structs originally came from the C language, which is 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++ for writing object-orientated programs, you will need to use classes. An analogy to understanding 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 of the two concepts.

Example Struct code

struct groceries

{

// members of the struct

string name;

int weight;

double price;

} chips, drinks; // Objects of the struct

Example class code

 
// Example of a class declaration in C++

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

class Groceries

{

// Members of the class

string name;

int weight;

double price;

int total();

};
Share this post