Junior — Middle
Can you explain what an abstract class is and how it differs from a regular class?
sobes.tech AI
Answer from AI
An abstract class is a class that is not intended to be instantiated directly, but serves as a base for other classes. In C++, an abstract class is defined by having at least one pure virtual function.
Differences between an abstract class and a regular class:
- You cannot create an object of an abstract class directly.
- It contains at least one pure virtual function, which must be implemented by derived classes.
- It is used to define an interface and common functionality that subclasses should inherit.
Example:
class AbstractBase {
public:
virtual void doSomething() = 0; // pure virtual function
};
class Derived : public AbstractBase {
public:
void doSomething() override {
// implementation
}
};
// AbstractBase obj; // error, cannot create an object of an abstract class
Derived d; // correct