C++ Structs

C++ Structs can be defined in such a way that classes and structs are blueprints that are used to create the instance of a class. (or) A Struct is a collection of data members of different data types and grouped under one name. It is also called an aggregate data type because it combines or aggregates the elements. And these structs are used for lightweight objects such as rectangle, color, point, etc;

C++ Structs Syntax, Examples

Syntax:

struct structure_name
{
//member declarations.
}

Creating the instance of Structure in C++

Structure variable can be defined as Student s;

Here, s is a structure variable of type Student. When the structure variable is created, the memory will be allocated. The student structure contains one char variable and two integer variables. Therefore, the memory for one char variable is 1 byte and two ints will be 2*4 = 8. Therefore total memory occupied by the s variable is 9 byte.

Example:

#include<iostream>    
using namespace std;    
 struct Rectangle      
{      
   int width, height;      
      
 };      
int main(void) {    
    struct Rectangle rec;    
    rec.width=8;    
    rec.height=5;    
   cout<<"Area of Rectangle is: "<<(rec.width * rec.height)<<endl;    
 return 0;    
}

Output:

Area of Rectangle is: 40

Example: Using Constructor and methods

#include<iostream>    
using namespace std;    
 struct Rectangle    {      
   int width, height;      
  Rectangle(int w, int h)      
    {      
        width = w;      
        height = h;      
    }      
  void areaOfRectangle() {       
    cout<<"Area of Rectangle is: "<<(width*height); }      
 };      
int main(void) {    
    struct Rectangle rec=Rectangle(4,6);    
    rec.areaOfRectangle();    
   return 0;    
}

Output:

Area of Rectangle is: 24

C++ Structure VS Class

Structure Class
If access specifier is not declared explicitly, then by default access specifier will be public. If access specifier is not declared explicitly, then by default access specifier will be private.
Syntax of Structure:

struct structure_name
{
// body of the structure
}

Syntax of Class:

class class_name
{
// body of the class
}

The instance of the structure is known as “Structure variable”. The instance of the class is known as “Object of the class”.