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
Show 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