0

I just read Code Complete 2nd Edition and there's a paragraph mentioned about overriding constructor.

The author gave an example of code tuning.

A program used a child class that was inherited from a parent class which is written from third party.

They found out that there's a needless initialization (in their use case) to set a field to system time in parent class constructor.

The author override the parent class constructor and initialized the filed to 0 instead of system time to reduce the system-level call.

My question is, how do we override a constructor? I always thought we have to inevitably call parent class constructor when creating a child object.

cwliang
  • 135
  • 11
  • 1
    If the book really explains this and gives a code example, surely you have your answer? I'm curious though, because I cannot imagine what such an example would look like. Maybe it's not a C++ book? – Asteroids With Wings Apr 28 '20 at 17:29

1 Answers1

2

No, you cannot do that in C++.

I don't have the text you're referring to, but if it really says that then it is wrong.

A derived class constructor can add further on-construction activities, and it can choose which base constructor to invoke, but it cannot prevent that base class constructor from doing its thing as originally designed, nor can it prevent any base class constructor from being called at all.

It may be possible in some other languages, though. For example, in Python, a derived constructor doesn't invoke a base constructor by default, so you have full control over both whether and how such a thing occurs, and you could arguably call this "overriding". Whether that leads to "good" program design is debatable.

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35
  • 2
    Derived class can however choose which of base class constructors it uses. – eerorika Apr 28 '20 at 17:30
  • @eerorika Indeed, but the base class constructors were always present and available, so this is not overriding. – Asteroids With Wings Apr 28 '20 at 17:31
  • The original Code Complete was more into the structure of code (and the principles behind designing it) than the nitty-gritty of any one language. Can't speak for the new version, but McConnell may not have been specifically referencing C++. – user4581301 Apr 28 '20 at 17:32