Search Your Topic

config
Thursday, 15 June 2017 06:03

C++ Structs

Written by
Rate this item
(0 votes)

In C++, 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++ Struct Example

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

 
  1. #include <iostream>  
  2. using namespace std;  
  3.  struct Rectangle    
  4. {    
  5.    int width, height;    
  6.     
  7.  };    
  8. int main(void) {  
  9.     struct Rectangle rec;  
  10.     rec.width=8;  
  11.     rec.height=5;  
  12.     cout<<"Area of Rectangle is: "<<(rec.width * rec.height)<<endl;  
  13.     return 0;  
  14. }  

Output:

Area of Rectangle is: 40

C++ 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.

 
  1. #include <iostream>  
  2. using namespace std;  
  3.  struct Rectangle    
  4. {    
  5.    int width, height;    
  6.   Rectangle(int w, int h)    
  7.     {    
  8.         width = w;    
  9.         height = h;    
  10.     }    
  11.   void areaOfRectangle() {     
  12.     cout<<"Area of Rectangle is: "<<(width*height); }    
  13.  };    
  14. int main(void) {  
  15.     struct Rectangle rec=Rectangle(4,6);  
  16.     rec.areaOfRectangle();  
  17.     return 0;  
  18. }  

Output:

Area of Rectangle is: 24

 

Read 29 times
Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email : anishsingh@live.com

toshiyas.in
More in this category: « C++ static C++ Enumeration »

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.