Classes and Objects in C++
Classes and objects are the fundamental building blocks of Object-Oriented Programming (OOP) in C++. A class defines a blueprint for objects, which are instances of the class. This allows developers to model real-world entities and their behaviors in code.
What is a Class?
A class is a user-defined data type that contains variables (data members) and functions (methods). It defines the structure and behavior of objects.
Example:
#include <iostream>
class Car {
public:
std::string brand;
int speed;
void display() {
std::cout << "Brand: " << brand << ", Speed: " << speed << " km/h" << std::endl;
}
};
What is an Object?
An object is an instance of a class. It is created from a class and can use the data members and methods defined in the class.
Example:
int main() {
Car car1; // Create an object of the Car class
car1.brand = "Toyota";
car1.speed = 120;
car1.display(); // Call the method
return 0;
}
Output:
Brand: Toyota, Speed: 120 km/h
Access Specifiers
Access specifiers determine the visibility of class members. C++ provides three access specifiers:
- Public: Members are accessible from anywhere.
- Private: Members are accessible only within the class.
- Protected: Members are accessible within the class and by derived classes.
Example:
#include <iostream>
class Car {
private:
std::string brand;
int speed;
public:
void setDetails(const std::string &b, int s) {
brand = b;
speed = s;
}
void display() {
std::cout << "Brand: " << brand << ", Speed: " << speed << " km/h" << std::endl;
}
};
int main() {
Car car1;
car1.setDetails("Ford", 150);
car1.display();
return 0;
}
Constructors
Constructors are special member functions that are automatically called when an object is created. They initialize the object's data members.
Example:
#include <iostream>
class Car {
public:
std::string brand;
int speed;
// Constructor
Car(const std::string &b, int s) {
brand = b;
speed = s;
}
void display() {
std::cout << "Brand: " << brand << ", Speed: " << speed << " km/h" << std::endl;
}
};
int main() {
Car car1("BMW", 200); // Constructor is called
car1.display();
return 0;
}
Destructors
Destructors are special member functions that are automatically called when an object is destroyed. They release resources or perform cleanup.
Example:
#include <iostream>
class Car {
public:
std::string brand;
Car(const std::string &b) {
brand = b;
std::cout << "Car " << brand << " created." << std::endl;
}
~Car() {
std::cout << "Car " << brand << " destroyed." << std::endl;
}
};
int main() {
Car car1("Audi");
return 0;
}
Output:
Car Audi created.
Car Audi destroyed.
Classes and objects in C++ provide a structured way to organize and reuse code, enabling developers to create robust and modular applications.