In C++, classes and structs are blueprints that are used to create the 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++ Structure is a collection of different data types. It is similar to the class that holds different types of data.
Syntax:
struct structure_name
{
//member declarations
}
Example
struct Student
{
char name[30];
int id;
int age;
}
How to create the instance of variable
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. Student structure contains one char variable and two integer variable. Therefore, the memory for one char variable is 1 byte and two ints will be 2*4 = 8.
How to access the variable of Structure
The variable of the structure can be accessed by simply using the instance of the structure followed by the dot (.) operator and then the field of the structure.
Program
/*Using Constructor and Method*/
#include <iostream>
#include <conio.h>
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() {
struct Rectangle rec=Rectangle(10,12);
rec.areaofRectangle();
getch();
return 0;
}
Output
Ares of Rectangle is : 120
No comments:
Post a Comment