Inherited Class Constructor/Code Cleanup

Started by
3 comments, last by leiavoia 17 years, 11 months ago
I have a small question/problem. I have been working on a project that uses a derived class whos parent class has a rather large constructor. The inherited class is intended to contain the same paramaters in its constructor as the parent class. Here is a very brief sample of my code format:
class Base{
  public:
     Base(int a, int b, int c) //The actual constructor is much larger
};

class Derived : Base{
  public:
     Derived(int a, int b, int c) : Base(a,b,c){};
};

So my question is pretty simple but I was having a little trouble finding a definitive answer through searches, books, articles etc. I understand that constructors are not inherited, but is there any way around having to write in all that extra functionality for the Derived class? Thanks in advance for any and all help, this community is awsome!
Advertisement
Unfortunately, there isn't. It's been one of many reasons of programmers cursing on C++.

But, to my knowledge, introducing contructor inheritance is being reviewed by C++ standard comitee (although I don't believe they will go through with it).
That's what I was afraid of. Thank you for the reply Deffer.

Edit: Oops, I posted this thread in the wrong forum. I meant to post it in the General section, sorry.
Quote:Original post by Westones3
I understand that constructors are not inherited, but is there any way around having to write in all that extra functionality for the Derived class?

you could use a template or even a macro to avoid having to type everything again :-)
However seriously: if you have any sort of significant initialization in your constructor, you may want to consider splitting its functionality into a separate init() function, that you simply call from your constructor.


A few things you can do, one already mentioned:

1) have an init() / reset() function. It doesn't get you around having to type in params, but it does delay it ;-)

2) defaults, in two flavors: internal and parameter defaults. Parameter defaults will save you some typing:

Thing::Thing( a=0, b=0, c=0 );

the other is just internal initialization:

Thing::Thing() {
// set myself up automatically.
// wait for user to override any defaults though other functions.
}

But other than that, get used to typing!

This topic is closed to new replies.

Advertisement