Senior
Is there a constructor in an abstract class?
sobes.tech AI
Answer from AI
Yes, an abstract class can have a constructor. An abstract class is a class that is not intended to be instantiated directly, but it can contain implementations, including a constructor.
The constructor of an abstract class is usually used to initialize common fields or perform shared logic that will be inherited by subclasses.
Example in C++:
class AbstractBase {
public:
AbstractBase(int value) : data(value) {}
virtual void doSomething() = 0; // pure virtual function
protected:
int data;
};
class Derived : public AbstractBase {
public:
Derived(int value) : AbstractBase(value) {}
void doSomething() override {
// implementation
}
};
Here, the constructor AbstractBase is called from the constructor of the derived class to initialize the data field. Thus, having a constructor in an abstract class is normal practice.