Classes and objects are fundamental concepts used to implement object-oriented programming (OOP). They provide a way to model real-world entities using data and behaviors. A class is a blueprint for creating objects, and an object is an instance of a class.
A class in C++ defines a new data type that can encapsulate both data (member variables) and functions (member functions or methods) that operate on that data. It serves as a template to create objects with similar characteristics.
class ClassName {
public:
// Public member variables and functions
int publicVariable;
void publicFunction();
private:
// Private member variables and functions
int privateVariable;
void privateFunction();
};
In this example:
class
keyword is used to define a class named ClassName
.An object is an instance of a class. When you create an object, you allocate memory for the class’s data members and can use its member functions.
ClassName obj; // Creates an object of ClassName
Let’s create a simple class named Car
with some attributes and behaviors.
#include <iostream>
using namespace std;
// Define a class named Car
class Car {
public:
// Attributes (member variables)
string brand;
string model;
int year;
// Behaviors (member functions)
void displayInfo() {
cout << "Brand: " << brand << ", Model: " << model << ", Year: " << year << endl;
}
};
int main() {
// Create an object of the Car class
Car myCar;
// Access and set the object's attributes
myCar.brand = "Toyota";
myCar.model = "Camry";
myCar.year = 2020;
// Call the object's member function
myCar.displayInfo();
return 0;
}
In this example:
Car
class has three public member variables: brand
, model
, and year
.displayInfo()
to print the details of the car.myCar
is created, and its attributes are set and accessed.C++ provides three access specifiers to control access to class members:
public
can be accessed from outside the class.private
can only be accessed within the class itself. This is the default access specifier if none is provided.protected
can be accessed by derived classes and within the class itself.#include <iostream>
using namespace std;
class Sample {
public:
int publicVar; // Accessible from anywhere
private:
int privateVar; // Accessible only within the class
protected:
int protectedVar; // Accessible within the class and derived classes
};
int main() {
Sample obj;
obj.publicVar = 10; // Allowed, as publicVar is public
// obj.privateVar = 20; // Error, privateVar is private
// obj.protectedVar = 30; // Error, protectedVar is protected
return 0;
}