Constructor in Abstract Class
Can you have a constructor in an abstract class? If yes, what is its purpose?
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 theName
member and prints a creation message.Warrior
is a concrete class that inherits fromCharacter
and calls the base class constructor to initialize theName
member.- When a
Warrior
object is created, theCharacter
constructor runs first, initializing common members and performing any necessary setup.
Purpose of Constructors in Abstract Classes
- Initialize Common Data Members: Constructors in abstract classes can initialize data members that are common to all derived classes, reducing redundancy and ensuring consistency.
- Setup and Validation: They can perform initial setup and validation tasks that are required before the derived class constructors run.
- Resource Management: Constructors in abstract classes can acquire resources that are needed by derived classes, ensuring proper resource management and initialization.
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.
Pure Virtual Functions
Learn how to create interfaces and abstract classes using pure virtual functions