🔷 What is an Object?
An object is an instance of a class. When you declare an object, you’re creating a real-world entity based on the structure defined in the class.
- A class is like a blueprint.
- An object is like the house built from that blueprint.
🔷 Syntax for Declaring Objects
ClassName objectName;
You can also declare multiple objects of the same class:
ClassName obj1, obj2, obj3;
🔷 Example: Declaring and Using an Object
#include <iostream>
using namespace std;
class Student {
public:
int rollNo;
string name;
void display() {
cout << "Roll No: " << rollNo << ", Name: " << name << endl;
}
};
int main() {
Student s1; // Declaration of object 's1' of class Student
// Assigning values
s1.rollNo = 101;
s1.name = "Alice";
s1.display(); // Calling member function using object
return 0;
}
🔷 Explanation
- Student is a class.
- s1 is an object of the
Student
class. - The object
s1
is used to access data members and member functions using the dot operator (.
): cppCopyEdits1.rollNo = 101; s1.display();
🔷 Types of Object Declaration
1. Static Declaration
Declared in a normal way (as in the example above). Memory is allocated automatically when the function is called and deallocated when the function ends.
Student s1; // Static object
2. Dynamic Declaration (Using Pointers)
Useful when you need objects at runtime.
Student *s1 = new Student;
s1->rollNo = 102;
s1->name = "Bob";
s1->display();
🔷 Real-Life Analogy
Class | Object Example |
---|---|
Blueprint | Actual house |
Car class | Honda, Toyota |
Student class | Ram, Sita |
🔷 Diagram (Text-Based)
Class: Student
------------------------
| rollNo : int |
| name : string |
| display() |
------------------------
Object: s1
------------------------
| rollNo = 101 |
| name = "Alice" |
------------------------
s1.display() --> calls the display() method
🔷 Summary
- Objects are instances of a class.
- You use objects to access class members (variables/functions).
- Use the dot operator (
.
) to access members:objectName.memberName
- You can declare objects statically or dynamically.