The core idea of Object-Oriented Programming revolves around two fundamental concepts: Classes and Objects.
A Class is a user-defined data type in C++. You can think of it as a blueprint or a template for creating objects. It defines what data the object will hold (attributes) and what operations it can perform (methods), but it does not allocate any memory for the data itself.
For example, a Car class might define that every car has a brand, a speed, and a method to accelerate().
In C++, a class is defined using the class keyword, followed by the class name. The class body is enclosed in curly braces and must end with a semicolon.
class Car {
public:
// Data members (Attributes)
string brand;
int speed;
// Member function (Method)
void accelerate() {
speed += 10;
cout << brand << " is now going " << speed << " km/h" << endl;
}
};An Object is an instance of a class. When a class is defined, no memory is allocated. Memory is only allocated when you create an object of that class.
If the Car class is the blueprint, then myToyota and myFord are the actual physical cars built from that blueprint.
Once a class is defined, you can create objects of that class type. You access the attributes and methods of an object using the dot (.) operator.
#include <iostream>
#include <string>
using namespace std;
class Car {
public:
string brand;
int speed;
void accelerate() {
speed += 10;
cout << brand << " is now going " << speed << " km/h" << endl;
}
};
int main() {
// 1. Create objects of class Car
Car car1;
Car car2;
// 2. Set attributes using the dot operator
car1.brand = "Toyota";
car1.speed = 50;
car2.brand = "Ford";
.) operator is used to access the members of an object.A user-defined data type that serves as a blueprint or template for creating objects.
An instance of a class that occupies memory and has state and behavior.
Data members are variables defined inside a class. Member functions are methods defined inside a class to manipulate the data.
Test your understanding with 3 questions
What is a class in C++?
Which operator is used to access members of an object in C++?
Does a class declaration allocate memory?
2 Modules
2 Modules