C plus plus Structs

In C plus plus, classes and structs are blueprints that are used to create instance of a class. Structs are used for lightweight objects such as Rectangle, color, Point etc.

Unlike class, structs in C++ are value type than reference type. It is useful if you have data that is not intended to be modified after creation of struct.


C plus plus Struct Example

Let’s see a simple example of struct Rectangle which has two data members width and height.

 
  • #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

 

C plus plus Struct Example: Using Constructor and Method

Let’s see another example of struct where we are using constructor to initialize data and method to calculate area of rectangle.

 
  • #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