Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does abstract base class need explicit default constructor?

For below code,

#include <iostream>

class virtualBase {
public:
  virtual void printName() = 0;

//   virtualBase() = default;

private:
  virtualBase(const virtualBase &) = delete; // Disable Copy Constructor
  virtualBase &
  operator=(const virtualBase &) = delete; // Disable Assignment Operator
};

class derivedClass : public virtualBase {
public:
  void printName() { std::cout << "Derived name" << std::endl; };
  derivedClass() {};
  ~derivedClass() = default;
};

int main() {
  derivedClass d;
  d.printName();
  return 0;
}

I need to uncomment the default constructor definition in base class for the compilation to succeed.

I am seeing the following compilation error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

test.cpp: In constructor ‘derivedClass::derivedClass()’:
test.cpp:18:18: error: no matching function for call to ‘virtualBase::virtualBase()’
   18 |   derivedClass() {};
      |                  ^
test.cpp:10:3: note: candidate: ‘virtualBase::virtualBase(const virtualBase&)’ <deleted>
   10 |   virtualBase(const virtualBase &) = delete; // Disable Copy Constructor
      |   ^~~~~~~~~~~
test.cpp:10:3: note:   candidate expects 1 argument, 0 provided

My understanding is that compiler provides it own default constructor esp in case like this where the class is really simple.

What am I missing here?

Thanks

>Solution :

Declaring any constructor explicitly prevents declaration of the implicit default constructor.

You do declare the copy constructor explicitly (even if you then define it as deleted).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading