In C++, you can declare objects of a class by using the class name followed by the object name. Here's an example using a simple class named `Person`:
```cpp
#include <iostream>
#include <string>
// Class declaration
class Person {
private:
string name;
int age;
public:
// Constructor
Person(string n, int a) : name(n), age(a) {}
// Member function to display person information
void displayInfo() const {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
// Declaring objects of the class
Person person1("John", 25);
Person person2("Alice", 30);
// Accessing and displaying information using member functions
cout << "Person 1: ";
person1.displayInfo();
cout << "Person 2: ";
person2.displayInfo();
return 0;
}
```
In this example:
- We have a `Person` class with private data members (`name` and `age`) and a public member function (`displayInfo`).
- The `Person` class has a constructor to initialize the data members when an object is created.
- In the `main()` function, we declare two objects (`person1` and `person2`) of the `Person` class.
- We then use the objects to access and display information using the `displayInfo` member function.
When you run this program, it will output information about the two persons:
```
Person 1: Name: John, Age: 25
Person 2: Name: Alice, Age: 30
```
Each object of the class has its own set of data members, and you can use these objects to perform operations and access the encapsulated data and behavior of the class.
Comments
Post a Comment