c-plus-plus
  1. c-plus-plus-structs

C++ Object Class Structs

Syntax

struct structName {
   dataType member1;
   dataType member2;
   ...
   dataType memberN;
} object1, object2, ..., objectM;

Example

#include<iostream>
using namespace std;

struct Rectangle {
   double length;
   double breadth;
};

int main() {
   Rectangle rect1 = {10.0, 5.0};
   Rectangle rect2 = {20.0, 15.0};

   double area1 = rect1.length * rect1.breadth;
   double area2 = rect2.length * rect2.breadth;

   cout << "Area of Rectangle 1: " << area1 << endl;
   cout << "Area of Rectangle 2: " << area2 << endl;

   return 0;
}

Output

Area of Rectangle 1: 50
Area of Rectangle 2: 300

Explanation

In C++, struct is a user-defined data type that is used to store a group of related data items of different data types. The data items in a struct are known as members. Structs can contain data members, functions, and constructors.

Use

Structs are used to group related data items together. They are commonly used in programming to create data types that combine different data items into a single unit. Structs are used in object-oriented programming to define objects that have properties and methods.

Important Points

  • Structs are user-defined data types.
  • Structs can contain data members, functions, and constructors.
  • Structs are used to group related data items together.
  • Structs are commonly used in programming to create data types that combine different data items into a single unit.

Summary

In summary, struct is a useful tool in C++ programming to group related data items together. Structs can be used to create user-defined data types that combine different data items into a single unit. Structs can contain data members, functions, and constructors. Structs are commonly used in object-oriented programming to define objects that have properties and methods.

Published on: