Structure & Function

Perform 'struct' with a function in C++.

How does a structure perform with a function in C++?

A structure is a user-defined data type that allows you to group variables of different data types under a single name. You can also include functions within a structure, making it a convenient way to encapsulate data and related functionality. Here's an example of a structure with a function in C++:

cpp Copy Code
#include<iostream>

// Define a structure called 'Person'
struct Person {
    // Data members
    std::string name;
    int age;

    // Member function to display information about the person
    void displayInfo() {
        std::cout << "Name: " << name << "\n";
        std::cout << "Age: " << age << " years\n";
    }
};

int main() {
    // Create an instance of the 'Person' structure
    Person person1;

 // Assign values to the data members
 person1.name = "AyaN";
 person1.age = 28;

    // Call the member function to display information
    person1.displayInfo();

    return 0;
}

In this example, the 'Person' structure has two data members ('name' and 'age') and one member function ('displayInfo'). The 'displayInfo' function is defined inside the structure and is capable of accessing the structure's data members. The 'main' function demonstrates how to create an instance of the structure, assign values to its data members, and call the member function to display information.

Output:
Name: AyaN
Age: 28 years

Note: Structures in C++ can also be used with classes, and the main difference between a class and a structure is the default access level (public for structures, private for classes).

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.