Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Abstract Class: constructor yes or no?

A class with one (or more) virtual pure functions is abstract, and it can't be used to create a new object, so it doesn't have a constructor.

I'm reading a book that provides the following example:

class Employee {    public:        Employee(const char*, const char*);        ~Employee();        const char* getFirstName() const;        const char* getLastName() const;          virtual double earnings() const=0  // pure virtual => abstract class        virtual void print() const    private:        char* firstName, lastName; }; 

If the class is abstract why we have a constructor? It uses this class later (Boss is public derived from Employee):

void Boss::Boss (const char* first, const char* last, double s)      : Employee (first, last) 
like image 417
user2452426 Avatar asked Nov 06 '13 09:11

user2452426


People also ask

Can abstract class have constructor yes or no?

Yes, an Abstract Class can have a Constructor.

Can an abstract base class have a constructor?

An abstract class can have a constructor similar to normal class implementation.

Can abstract class can have constructor in C#?

Yes, an abstract class can have a constructor, even though an abstract class cannot be instantiated.


2 Answers

You're correct when you say that a class that has a pure virtual function is abstract and can't be instantiated. But you're wrong when you say that it can't have a constructor.

Indeed, as your example show, an abstract class can have private members, that may be used by member functions of this class. And these members must be initialized. A constructor is a way to do that (e.g. with an initialization list in the derived class, as your second sample shows), better in my opinion than an init() function for example.

Editing my comment in the answer: An abstract class can have member variables and potentially non-virtual member functions, so that every derived class from the former implements specific features.

Then, the responsibility for the initialization of these members variables may belong to the abstract class (at least always for private members, because the derived class wouldn't be able to initialize them, yet could use some inherited member functions that may use/rely on these members). Thus, it makes it perfectly reasonable for abstract classes to implement constructors.

like image 110
JBL Avatar answered Oct 10 '22 21:10

JBL


A class with a pure virtual function can't be instantiated. It is expected to have sub-classes that will extend it and provide the missing functionality.

These sub-classes will construct the base class when they are instantiated, they will call the constructor of their super class which is why abstract classes have constructors in c++.

So you can't create an instance directly and call the constructor directly but future sub-classes will.

like image 45
odedsh Avatar answered Oct 10 '22 21:10

odedsh