Welcome to our deep dive into C++ Abstract Classes! In this lesson, we'll learn about what abstract classes are, why we need them, and how to create and use them in our code. Let's get started! š
An abstract class is a class that cannot be instantiated (created as an object) but can be inherited by other classes. It is used as a base class to provide a common interface for its child classes.
In C++, an abstract class is declared using the virtual keyword with a pure (= 0) function. A pure function is a function without an implementation (also known as a pure virtual function).
Here's an example of a simple abstract class named Shape:
#include <iostream>
class Shape {
public:
// Pure virtual function
virtual void draw() = 0;
};In this example, we have created a class Shape with a pure virtual function draw(). Since draw() is a pure virtual function, the Shape class cannot be instantiated.
An abstract class can have both concrete (implemented) and abstract (pure virtual) members. However, once a class has at least one pure virtual function, the entire class becomes abstract.
Abstract classes can be used as base classes for other classes through inheritance. When a class inherits from an abstract class, it must implement all the pure virtual functions of the base class, or the derived class also becomes abstract.
Let's create a simple example using the Shape abstract class:
#include <iostream>
#include <string>
class Shape {
public:
std::string name;
// Pure virtual function
virtual void draw() = 0;
};
class Circle : public Shape {
public:
void draw() {
std::cout << "Drawing a circle." << std::endl;
}
};
class Rectangle : public Shape {
public:
void draw() {
std::cout << "Drawing a rectangle." << std::endl;
}
};
int main() {
Circle circle;
Rectangle rectangle;
circle.name = "Circle";
rectangle.name = "Rectangle";
circle.draw();
rectangle.draw();
return 0;
}In this example, we have created a Circle and Rectangle classes that inherit from the Shape abstract class. Both the Circle and Rectangle classes implement the draw() function, and the main() function demonstrates how to use these derived classes.
What is an abstract class in C++?
That's it for our C++ Abstract Classes lesson! I hope this tutorial helps you understand the concepts better, and feel free to reach out if you have any questions or need further clarification. Happy coding! š¤š