C++ Classes
In C++, classes are a core concept of object-oriented programming (OOP). A class is a blueprint for creating objects, bundling data and functions that operate on the data into one structure.
Basic Syntax of a Class
A class defines attributes (data members) and methods (member functions), and you can create objects from a class.
Basic Example of a Class:
cpp#include
class Rectangle {
// Private data members
private:
int width;
int height;
// Public member functions
public:
// Constructor to initialize attributes
Rectangle(int w, int h) {
width = w;
height = h;
}
// Member function to calculate area
int area() {
return width * height;
}
// Member function to calculate perimeter
int perimeter() {
return 2 * (width + height);
}
};
int main() {
// Create an object of class Rectangle
Rectangle rect(10, 5);
// Access member functions using the object
std::cout << "Area: " << rect.area() << std::endl; // Output: 50
std::cout << "Perimeter: " << rect.perimeter() << std::endl; // Output: 30
return 0;
}
Components of a Class
-
Data Members: Variables that hold data specific to an object (also called attributes or properties).
- In the example,
widthandheightare data members of theRectangleclass.
- In the example,
-
Member Functions: Functions that operate on the class's data members (also called methods).
- In the example,
area()andperimeter()are member functions.
- In the example,
-
Access Specifiers: Control the access level of data members and member functions. They are:
private: Members are only accessible within the class.public: Members are accessible from outside the class.protected: Members are accessible within the class and by derived classes (used in inheritance).
In the example,
widthandheightare private, whilearea()andperimeter()are public. -
Constructor: A special member function used to initialize objects. It has the same name as the class and no return type.
- In the example,
Rectangle(int w, int h)is a constructor that initializes thewidthandheight.
- In the example,
Accessing Class Members
Class members are accessed using the dot operator (.) on an object of the class.
cppRectangle rect(10, 5); // Create an object of Rectangle
std::cout << rect.area(); // Call the area() method of the object
Constructors and Destructors
-
Constructor: Initializes the object when it's created. You can define multiple constructors with different parameters (constructor overloading).
-
Destructor: Cleans up when an object is destroyed. It is named with a tilde
~followed by the class name and has no return type. It is automatically called when the object goes out of scope.
Example of Constructor and Destructor:
cppclass Rectangle {
public:
int width, height;
// Default constructor
Rectangle() {
width = 0;
height = 0;
std::cout << "Rectangle created!" << std::endl;
}
// Parameterized constructor
Rectangle(int w, int h) : width(w), height(h) {}
// Destructor
~Rectangle() {
std::cout << "Rectangle destroyed!" << std::endl;
}
};
Encapsulation
Encapsulation is the concept of bundling data (attributes) and methods (functions) inside a class and restricting
access to some components using access specifiers (private, public, etc.).
- The data members are typically private, while member functions are public to allow controlled access to the data.
cppclass Rectangle {
private:
int width, height;
public:
// Constructor
Rectangle(int w, int h) : width(w), height(h) {}
// Public getter and setter functions to access private members
void setWidth(int w) { width = w; }
int getWidth() { return width; }
int area() { return width * height; }
};
In this example, width is private, and the public functions setWidth() and
getWidth() provide controlled access to it.
Inheritance
Inheritance allows one class (derived class) to inherit properties and behaviors (data members and member functions) from another class (base class). This promotes code reuse.
Example of Inheritance:
cpp// Base class
class Shape {
public:
void setWidth(int w) { width = w; }
void setHeight(int h) { height = h; }
protected:
int width;
int height;
};
// Derived class
class Rectangle : public Shape {
public:
int area() {
return width * height; // Uses inherited members width and height
}
};
int main() {
Rectangle rect;
rect.setWidth(5);
rect.setHeight(10);
std::cout << "Area: " << rect.area() << std::endl; // Output: 50
return 0;
}
In this example, Rectangle inherits from Shape and can use the setWidth()
and setHeight() functions from the Shape class.
Polymorphism
Polymorphism allows functions to take many forms, enabling the same function to behave differently depending on the object calling it. In C++, this can be achieved using function overriding and virtual functions.
-
Function Overriding: When a derived class defines a function that is already present in the base class with the same signature.
-
Virtual Functions: A function in a base class that can be overridden in derived classes. A base class function must be marked with
virtualto allow overriding.
Example of Polymorphism:
cppclass Shape {
public:
virtual void draw() { // Base class version
std::cout << "Drawing a shape" << std::endl;
}
};
class Circle : public Shape {
public:
void draw() override { // Derived class version
std::cout << "Drawing a circle" << std::endl;
}
};
int main() {
Shape* shape;
Circle circle;
shape = &circle;
shape->draw(); // Calls Circle's version of draw() due to polymorphism
return 0;
}
Abstraction
Abstraction hides complex implementation details and shows only the essential features of an object. In C++, abstract classes are defined using pure virtual functions.
- A pure virtual function is a function that has no implementation in the base class and is
declared by assigning
0to the function.
Example of Abstraction:
cppclass Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
class Circle : public Shape {
public:
void draw() override {
std::cout << "Drawing a circle" << std::endl;
}
};
int main() {
Circle circle;
circle.draw(); // Calls the Circle's implementation of draw()
return 0;
}
In this example, Shape is an abstract class because it contains a pure virtual function,
draw(). Derived classes like Circle must implement the draw() function.
Summary
- Classes in C++ are used to model real-world objects by encapsulating data and functions into one entity.
- Encapsulation, Inheritance, Polymorphism, and Abstraction are key concepts of object-oriented programming that C++ supports.
- C++ classes allow for the creation of reusable, maintainable, and modular code by bundling related data and behavior into objects.