Yes, you can have a constructor in an abstract class. Although you cannot instantiate an abstract class directly, its constructors are called when a derived class object is created.
The purpose of the constructor in an abstract class is to initialize common data members and perform any setup required for the base part of the derived objects.
Here’s an example:
#include <iostream>
#include <string>
// Abstract base class with a constructor
class Character {
public:
Character(const std::string& name)
: Name(name) {
std::cout << "Character created: "
<< Name << "\n";
}
virtual std::string GetName() = 0;
protected:
std::string Name;
};
class Warrior : public Character {
public:
Warrior(const std::string& name)
: Character(name) {}
std::string GetName() override {
return Name;
}
};
int main() {
Warrior warrior("Aragon");
std::cout << "Warrior's name: "
<< warrior.GetName() << "\n";
}
Character created: Aragon
Warrior's name: Aragon
In this example:
Character
is an abstract class with a constructor that initializes the Name
member and prints a creation message.Warrior
is a concrete class that inherits from Character
and calls the base class constructor to initialize the Name
member.Warrior
object is created, the Character
constructor runs first, initializing common members and performing any necessary setup.Using constructors in abstract classes helps ensure that all derived objects are correctly initialized and adhere to a common setup routine, even though the abstract class itself cannot be instantiated.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to create interfaces and abstract classes using pure virtual functions