User-defined data types (Data Types and Variables)

In C++, user-defined data types are types that are defined by the programmer instead of being built into the language. User-defined data types allow programmers to create custom types that represent specific entities or concepts in their programs.

There are two primary ways to define user-defined data types in C++: struct and class.

1. Struct: A struct is a collection of data members that can have different data types. The members of a struct are accessed using the dot operator (.). Here's an example of defining a struct in C++:

struct Person {
string name;
int age;
};

In this example, we define a struct called Person with two data members: name of type string and age of type int.

2. Class: A class is a user-defined data type that encapsulates data members and member functions. The data members of a class can be accessed using the dot operator (.), just like a struct. However, classes can also have member functions, which are functions that operate on the data members of the class. Here's an example of defining a class in C++:

class Rectangle {
private: int length; int width;
public: void setLength(int l) { length = l; } void setWidth(int w) { width = w; } int area() { return length * width; }
};

In this example, we define a class called Rectangle with two private data members: length and width. We also define three member functions: setLength, setWidth, and area. The setLength and setWidth functions are used to set the values of the data members, while the area function calculates the area of the rectangle using the length and width data members.

Once a struct or class is defined, it can be used to declare variables of that type. Here's an example of using the Person struct to declare a variable:

Person john; john.name = "John Smith"; john.age = 30;

In this example, we declare a variable called john of type Person. We then set the name and age data members of the john variable using the dot operator.

Similarly, here's an example of using the Rectangle class to declare a variable:

Rectangle myRect; myRect.setLength(5); myRect.setWidth(10); int myArea = myRect.area();

In this example, we declare a variable called myRect of type Rectangle. We then use the setLength and setWidth member functions to set the values of the length and width data members. Finally, we use the area member function to calculate the area of the rectangle and store it in the myArea variable.

In summary, user-defined data types in C++ allow programmers to create custom types that represent specific entities or concepts in their programs. Structs and classes are the two primary ways to define user-defined data types in C++, and they can be used to declare variables of that type, set values for their data members, and call member functions to operate on those data members. 

Post a Comment

Previous Post Next Post