|
In C++, a concrete class is a class that can be instantiated to create objects, while an abstract class cannot be instantiated and typically contains at least one pure virtual function. Here's a simple C++ program to illustrate the difference between a concrete class and an abstract class:
#include <iostream>
using namespace std;
// Abstract Class
class AbstractClass {
public:
// Pure virtual function
virtual void display() = 0;
// Concrete method
void show() {
cout << "This is a concrete method in an abstract class." << endl;
}
};
// Concrete Class
class ConcreteClass : public AbstractClass {
public:
// Implementation of the pure virtual function
void display() override {
cout << "This is the implementation of the pure virtual function in a concrete class." << endl;
}
};
int main() {
// AbstractClass obj; // This will cause a compilation error
ConcreteClass obj; // Instantiating the concrete class
obj.display(); // Calling the implemented method
obj.show(); // Calling the concrete method from the abstract class
return 0;
}
Explanation:
- Abstract Class:
- Defined using the keyword `class`.
- Contains a pure virtual function: `virtual void display() = 0;`.
- Cannot be instantiated directly.
- Concrete Class:
- Inherits from the abstract class: `class ConcreteClass : public AbstractClass`.
- Implements the pure virtual function: `void display() override`.
- Can be instantiated to create objects.
In the `main()` function, attempting to instantiate `AbstractClass` will result in a compilation error, while instantiating `ConcreteClass` is allowed and we can call both the implemented pure virtual function and the inherited concrete method.
This example illustrates the key differences between concrete and abstract classes in C++. Feel free to experiment with this code and let me know if you have any questions or need further details! 🚀
Comments
Post a Comment