Difference Between Structure and Class

Computer ProgrammingProgrammingMiscellaneous

In this post, we will understand the difference between structure and class.

Class

  • It is defined using ‘class’ keyword.

  • When data is defined in a class, it is stored in memory as a reference.

  • It gets memory allocated only when an object of that class is created.

  • The reference type (before creating an object) is allocated on heap memory.

  • They can have constructors and destructors.

  • It can use inheritance to inherit properties from base class.

  • The ‘protected’ access modifier can be used with the data members defined inside the class.

Structure

  • The ‘struct’ keyword is used to define a structure.

  • Every member in the structure is provided with a unique memory location.

  • When the value of one data member is changed, it doesn’t affect other data members in structure.

  • It helps initialize multiple members at once.

  • Total size of the structure is equivalent to the sum of the size of every data member.

  • It is used to store various data types.

  • It takes memory for every member which is present within the structure.

  • A member can be retrieved at a time.

  • It supports flexible arrays.

  • Its instance can be created without a keyword.

  • It doesn’t support protected access modifier.

  • It doesn’t support inheritance.

  • It doesn’t have a constructor or destructor.

  • The values allocated to structures are stored in stack memory.

raja
Published on 24-Mar-2021 14:00:45
Advertisements