Skip to content
Home ยป Access to member variables from objects

Access to member variables from objects

๐Ÿ”ท 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 class Student.
  • s1.rollNo and s1.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 SpecifierAccess from ObjectAccess 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 and set methods in C++.

๐Ÿ”ท Summary

  • Use the dot operator to access member variables: cppCopyEditobjectName.variableName;
  • Public variables can be accessed directly.
  • Private variables need to be accessed through member functions.
  • This ensures security and encapsulation in OOP.