Person Class in C++ with Details Function

In this exercise, you will create a C++ class called "Person" that includes attributes such as name and age. The class will also include a member function to print the details of a person. This task will help you practice object-oriented programming (OOP) concepts such as class definition, constructors, and member functions. It will also give you experience with managing class attributes and displaying information in a structured format.

Group

Object-Oriented Programming in C++

Objective

1. Define a class called "Person" with the attributes "name" (string) and "age" (integer).
2. Add a constructor that takes name and age as parameters.
3. Implement a member function to print the details of the person (name and age).
4. Create an object of the class in the main function and call the function to display the person's details.

Create a class Person with attributes like name, age, and a function that prints their details.

Example C++ Exercise

 Copy C++ Code
#include <iostream>  // Include the standard input/output library
#include <string>    // Include the string library for string manipulation
using namespace std;

// Define the 'Person' class
class Person {
private:
    string name;  // Private attribute for name
    int age;      // Private attribute for age

public:
    // Constructor to initialize the 'Person' object with name and age
    Person(string personName, int personAge) {
        name = personName;  // Initialize name
        age = personAge;    // Initialize age
    }

    // Member function to print the details of the person
    void printDetails() {
        cout << "Name: " << name << ", Age: " << age << endl;  // Print name and age
    }
};

int main() {
    // Create an object of the 'Person' class with name "John" and age 30
    Person person1("John", 30);

    // Call the printDetails function to display the person's details
    person1.printDetails();  // Output: Name: John, Age: 30

    return 0;  // Return 0 to indicate successful execution
}

 Output

Name: John, Age: 30

Share this C++ Exercise


More C++ Programming Exercises of Object-Oriented Programming in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.