Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does "Constructor of an abstract class" exists?

Tags:

c++

We can not create an object of abstract class. And constructors create new instances of any class which is called as an object.

This is what I know about the constructor, class and object relationship.

Please correct me if I am wrong.

like image 706
Priyanka Avatar asked Jan 17 '26 18:01

Priyanka


2 Answers

Does it exist?

#include <iostream>

class A
{
public:
    virtual void f() = 0;
    A()
    {
        std::cout << "Yes it does!" << std::endl;
    }
};

class B: public A
{
public:
    void f() {}
};

int main()
{
    B b;
    return 0;
}

Yes it does!

The technical reason is that somebody needs to initialize the members of A and that's the job of the constructor. But you can easily reason it as follows:

The inheritance relation is often termed with "is". For example, an object of type B is also of type A. In other words B is a kind of A. The constructor of A constructs an object of type A. But b above is also a kind of A, so A must have a constructor to be able to construct it.

like image 88
Shahbaz Avatar answered Jan 19 '26 16:01

Shahbaz


Yes! It has to exist, since constructors of any child class make a call to the base constructor. (This is the simplest way to explain it)

like image 34
Eutherpy Avatar answered Jan 19 '26 16:01

Eutherpy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!