๐ท What Are Member Variables?
Member variables (also called data members) are variables declared inside a class. These variables hold the data for each object.
Each object of a class gets its own copy of the member variables.
๐ท Accessing Member Variables from Objects
To access member variables, we use the dot operator (.) with the object name.
โ Syntax:
objectName.variableName;
This allows you to read or assign values to the variable.
๐ท Example: Accessing Member Variables
#include <iostream>
using namespace std;
class Student {
public:
int rollNo;
string name;
};
int main() {
Student s1; // Object of class Student
// Accessing member variables using object
s1.rollNo = 101;
s1.name = "Alice";
// Displaying values
cout << "Roll Number: " << s1.rollNo << endl;
cout << "Name: " << s1.name << endl;
return 0;
}
๐ท Explanation:
s1is an object of classStudent.s1.rollNoands1.nameare used to access the public member variables.- You can assign values or print values using this syntax.
๐ Private Member Variables and Access
If member variables are private, they cannot be accessed directly using the object.
Example:
class Student {
private:
int rollNo;
public:
void setRollNo(int r) {
rollNo = r;
}
int getRollNo() {
return rollNo;
}
};
int main() {
Student s1;
// s1.rollNo = 101; // โ Error: 'rollNo' is private
s1.setRollNo(101); // โ
Allowed via public function
cout << "Roll No: " << s1.getRollNo() << endl;
}
๐ธ This is a principle of encapsulation: keeping data safe and accessible only through controlled functions (getters/setters).
๐ท Table: Access Based on Specifier
| Access Specifier | Access from Object | Access in Class Functions |
|---|---|---|
public | โ Yes | โ Yes |
private | โ No | โ Yes |
protected | โ No | โ Yes (in derived classes) |
๐ท Real-Life Analogy
Think of a bank account class:
- balance is a private member variable.
- You can’t take money directly (not safe!).
- You use deposit() and withdraw() functions to access it safely โ just like you use
getandsetmethods in C++.
๐ท Summary
- Use the dot operator to access member variables: cppCopyEdit
objectName.variableName; - Public variables can be accessed directly.
- Private variables need to be accessed through member functions.
- This ensures security and encapsulation in OOP.
