Sunday, 3 May 2020

Difference Between Structure and Class in C++


Both Structure and Class are user-defined data types and they can be further used to create instances.

Structure
A structure is a collection of variables of different data types. It creates a data type that can be used to grouped different items under a single unit. It is almost similar to a class but they have many differences.

Class
A class is a user-defined blueprint from which objects are created. A class in C++ is the building block, that leads to Object-Oriented programming. It holds its own data members and member functions, which can be accessed and used by creating an instance, called object, of that class.   Basically, a class combines the fields and methods(member function which defines actions) into a single unit.

Differences between Structure and Class in C++
The Mian differences between class and structure are discussed below.
Structure:

  • A structure is a value type and its object is created on the stack memory.
  • A structure does not support inheritance.
  • A structure can only have the parameterized constructor. It has not non-parametrized constructor, default constructor, and destructor also.
  • In structure, data members are by default public.
  • A structure does not support data hiding like class.
  • A structure only contains data members.
  • The member variable of structure can not be initialized directly.
  • .An object of a structure is created in stack memory.
  • A structure's object can be created without using a `new` keyword.


Class: 

  • A class is of a reference type and its object is created on heap memory.
  • A class support inheritance and one class can inherit another class.
  • A class can have all types of constructor and destructor, parameterized, and non-parameterized.
  • A class has all data members private by default.
  • A class support data hiding which is accomplished by providing three access specifiers that are “public”, “private”, “protected”.
  • A class contains data members and member functions too.
  • A class member variable can be initialized directly.
  • An object of a class is created in heap memory.
  • An object of a class can't be created without using a `new` keyword.