🔷 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:
s1
is an object of classStudent
.s1.rollNo
ands1.name
are 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
get
andset
methods 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.