OOP: CLASSES AND OBJECTS
What is an Object?
An object is a real instance of a class.
If a class is a blueprint, an object is the actual thing created from that blueprint.
Student mina;
Student riaz;
Here, mina and riaz are two different objects of the Student class.
Object Has Three Ideas
1. State
State means the data stored in the object.
Example:
name = "Mina"
marks = 85
2. Behavior
Behavior means what the object can do.
Example:
display details
update marks
check pass/fail
3. Identity
Identity means each object is distinct, even if two objects contain the same data.
Student a;
Student b;
a and b are separate objects.
Important Point
Each object has its own copy of non-static data members.
If mina and riaz both have a marks data member, changing mina's marks does not automatically change riaz's marks.
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 first;
Student second;
first.setName("Mina");
second.setName("Riaz");
first.display();
second.display();
}
Viva Answer
An object is an instance of a class. It has state, behavior, and identity. Each object has its own copy of non-static data members.
Quick Check
- What is an object?
- What is object state?
- What is object behavior?
- If two objects have the same data, are they the same object?