Classes and Objects
In Object-Oriented Programming, classes and objects are the basic building blocks. They help organize code in a way that reflects real-world things.
A class is a blueprint or template used to create objects. It defines the properties (also called attributes or data members) and behaviors (also called methods or functions) that the object will have. However, a class by itself does not take up memory—it only defines the structure.
class Car {
public:
string brand;
int speed;
void start() {
cout << "Car has started" << endl;
}
void accelerate() {
speed += 10;
}
};
In this example, Car is a class with two data members (brand, speed) and two member functions (start(), accelerate()).
An object is a real, usable instance of a class. When an object is created, memory is allocated for its data members. Each object has its own copy of the data but can use the functions defined in the class.
Car myCar; // myCar is an object of class Car
myCar.brand = "Toyota";
myCar.speed = 0;
myCar.start(); // Calls start() function
myCar.accelerate(); // Increases speed by 10
Here, myCar is an object of the Car class. It has its own values for brand and speed and can perform actions like starting and accelerating.
Think of a class as a recipe for baking a cake. The recipe tells you what ingredients are needed and the steps to follow. But the actual cake you bake using that recipe is the object. You can bake many cakes (objects) using the same recipe (class).
This approach makes code organized, reusable, and easier to manage.
Open this section to load past papers