user defined constructor for an abstract class

83 Views Asked by At

I've searched if constructor exists for an abstract class. I found that the answer is YES, and these constructors can be called or used by derived class objects.

How about user defined constructors for an abstract class??

Can we write or define Default, parametrized or copy constructors for an abstract class??

2

There are 2 best solutions below

0
On

How about user defined constructors for an abstract class??

Yes,

Can we write or define Default, parametrized or copy constructors for an abstract class??

Yes

Abstract class cannot instantiate, and since it meant as a base class, you should define a virtual destructor for it.

DEMO: http://coliru.stacked-crooked.com/a/a4b851e70667bb59

0
On

It is common to have protected constructors in a base class: they are meant to initialize the private variable of the class. They are called implicitly or explicitly for constructors of derived classes:

  • default of copy constructors are called implicitly
  • parameterized constructors must be called explicitly

Example :

class Base {
    private int i;
public:
    Base(int val) {
        i = val;
    }
    virtual ~Base() { // always a virtual dtor in base class ...
    }
    // other methods ...
};
class Derived: public Base {
...
public:
    Derived(): Base(0) { // explicit call necessary because no default ctor in Base
        ...
    }
    ...
};

The virtual destructor is recommended because it ensures that if any subclass has a custom destructor it will be called.