OOP: CLASSES AND OBJECTS
Accessing Members
To use an object, you call its public member functions or access its public data.
In good OOP, data is usually private, and outside code uses public methods.
Dot Operator .
Use the dot operator when you have an object.
student.display();
Example:
#include <iostream>
#include <string>
class Student {
private:
std::string name;
public:
void setName(const std::string& studentName) {
name = studentName;
}
void display() const {
std::cout << name << '\n';
}
};
int main() {
Student student;
student.setName("Mina");
student.display();
}
Arrow Operator ->
Use the arrow operator when you have a pointer to an object.
studentPtr->display();
This means:
(*studentPtr).display();
Example:
#include <iostream>
#include <memory>
#include <string>
class Student {
private:
std::string name;
public:
void setName(const std::string& studentName) {
name = studentName;
}
void display() const {
std::cout << name << '\n';
}
};
int main() {
auto studentPtr = std::make_unique<Student>();
studentPtr->setName("Riaz");
studentPtr->display();
}
Public vs Private Access
Outside code can only access public members.
class Student {
private:
int marks;
public:
void setMarks(int value) {
marks = value;
}
};
This is allowed:
student.setMarks(90);
This is not allowed:
// student.marks = 90; // error: marks is private
Why Prefer Methods?
Methods can protect rules.
For example, a setter can reject negative marks. Direct public data cannot protect itself.
Viva Answer
Use . to access public members through an object and -> to access public members through a pointer to an object. Private members cannot be accessed directly from outside the class.
Quick Check
- When do you use
.? - When do you use
->? - What does
ptr->display()mean internally? - Why should data usually be private?