C++ Structure and Function

You can use the examples in this article to pass structures as arguments to functions and use them in your programs.

Similar to regular arguments, structure variables can be passed to a function and returned.

Passing structure to function in C++

Like a normal argument, a structure variable can be passed to a function. Think of this illustration:


Example 1: C++ Structure and Function

#include <iostream>
#include <string>

using namespace std;

// Structure to represent a person
struct Person {
    string name;
    int age;
};

// Function to display information about a person
void displayPerson(const Person& person) {
    cout << "Name: " << person.name << endl;
    cout << "Age: " << person.age << endl;
}

int main() {
    // Create a person object
    Person p1;
    
    // Set the values of the person object
    p1.name = "John Doe";
    p1.age = 30;
    
    // Display the information of the person
    displayPerson(p1);
    
    return 0;
}
OUTPUT:
Name: John Doe
Age: 30

we define a structure called Person that has two members: name and age. We also define a function called displayPerson that takes a Person object as a parameter and displays its information.

In the main function, we create a Person object named p1 and set its name and age attributes. Then, we call the displayPerson function to display information of the p1 object.


Example 2: Returning structure from function in C++

#include <iostream>
#include <string>

using namespace std;

// Structure to represent a person
struct Person {
    string name;
    int age;
};

// Function to create and return a person object
Person createPerson(const string& name, int age) {
    Person person;
    person.name = name;
    person.age = age;
    return person;
}

int main() {
    // Create a person object using the createPerson function
    Person p = createPerson("John Doe", 30);
    
    // Display the information of the person
    cout << "Name: " << p.name << endl;
    cout << "Age: " << p.age << endl;
    
    return 0;
}
OUTPUT:
Name: John Doe
Age: 30

In this example, we define a structure called Person with two members: name and age. We also define a function called createPerson that takes a name and an age as parameters and returns a Person object.

Inside the createPerson function, we create a Person object set its name and age attributes using the function parameters, and then return the Person object.

In the main function, we call the createPerson function, passing the name “John Doe” and age 30. The returned Person object is stored in the variable p. We then display the information of the person using the name age attributes of the Person object.

Leave a Reply

Your email address will not be published. Required fields are marked *