3

I read this question "C++ Abstract Class: constructor yes or no?" and the answers belonging to it.

But according to answers, I understand that we need the constructor to initialize it data members, however I can use its member functions like setter functions in my derived class to initialize the data members, so Why is it important to define a constructor?

Community
  • 1
  • 1
Mahmoud Emam
  • 1,499
  • 4
  • 20
  • 37
  • 5
    The constructor (if called) guarantees the correct initial state of the object. Setters might never be called? – StuartLC May 02 '14 at 18:50

2 Answers2

2

The default constructor definition and the member initializations make the class self contained regarding proper setup conditions (valid state).
Usage of setter methods to manipulate the class instance is optional for class clients (including inheriting classes).

You may consider adding more constructor signatures, that the clients can use to inititialze the class members with a single call, and don't require these applying additional setter calls.

It depends on the particular use case, what's more convenient and semantically correct in the end.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • Yes, adding more constructor signatures will be useful for the clients if they are going to create objects but in case of abstract classes no way to create objects. – Mahmoud Emam May 02 '14 at 19:05
  • @M_E Abstract classes are intended to be inherited, so what are you bothering about? If you want to have pure abstract interfaces, don't introduce data members (but rather virtual getter/setter methods) at all! – πάντα ῥεῖ May 02 '14 at 19:08
  • 2
    @M_E: A derived constructor _can and does_ call the constructor of a pure virtual base class. Always. – Mooing Duck May 02 '14 at 19:14
1

Two reasons:

  1. To ensure the objects are always within a valid state.
  2. You need a copy constructor to ensure that data gets copied correctly (e.g., no blind copies of dynamically allocated resources).

Probably more.

user3344003
  • 20,574
  • 3
  • 26
  • 62