Difference Between Class and Object in C++ expalin in detail
Difference Between Class and Object in C++
| Aspect | Class | Object |
|---|---|---|
| Definition | A blueprint or template that defines data members and functions but doesn’t occupy memory itself. | A real instance of a class that occupies memory and holds actual data. |
| Nature | Abstract concept | Concrete entity |
| Memory | No memory allocation until object is created | Memory is allocated when an object is created |
| Usage | Defines properties and behaviors | Used to access the properties and behaviors defined by the class |
| Example | class Car { /* members */ }; |
Car car1; creates an object car1 of class Car |
| Purpose | Acts as a template to create objects | Represents an actual entity with state and behavior |
Explanation:
A Class is like a blueprint or plan for creating objects. It describes what data and methods the objects will have. It’s a user-defined data type.
An Object is a specific instance of the class. When you create an object, memory is allocated and you can use it to access the class’s variables and functions.
#include <iostream>
using namespace std;
// Define a class named Car
class Car {
public:
string brand;
int year;
void displayInfo() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};
int main() {
// Create an object car1 of class Car
Car car1;
// Access and set data members
car1.brand = "Honda";
car1.year = 2020;
// Call member function
car1.displayInfo(); // Output: Brand: Honda, Year: 2020
return 0;
}
Here, Car is the class — it describes what a car is.
car1 is an object — a real car with brand "Honda" and year 2020.
Comments
Post a Comment