In C++, you can access member variables (also known as data members) of a class using the dot (`.`) operator. Here's an example demonstrating how to access member variables from objects:
#include <iostream>
#include <string>
using namespace std;
// 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() {
// Creating an object of the class
Person person1("John", 25);
// Accessing and displaying individual member variables
cout << "Name: " << person1.name << ", Age: " << person1.age << endl;
// Accessing and displaying information using the member function
cout << "Using member function: ";
person1.displayInfo();
return 0;
}
In this example:
- We have a `Person` class with private data members (`name` and `age`).
- The `Person` class has a constructor to initialize the data members when an object is created.
- In the `main()` function, we create an object (`person1`) of the `Person` class.
- We directly access the individual member variables (`name` and `age`) using the dot (`.`) operator and print them.
- We also access and display information using the `displayInfo` member function.
However, note that accessing private member variables directly from outside the class is not a good practice because it breaks encapsulation. In a well-designed class, member variables are often declared as private, and access to them is controlled through public member functions (getters and setters). This ensures better encapsulation and allows you to enforce constraints or perform actions when accessing or modifying the data. The example above directly accessing private member variables is for illustrative purposes; in practice, you should use public member functions to access and modify private member variables.
Comments
Post a Comment