Hello everyone,
I noticed in some code, in a derived class, the constructor will be written in a way like this, my question is whether it is good code to add base()? Because I think
- base() will be implicitly called for derived class constructor if we do not pass any parameters to base class;
- if we need to pass any parameters, I think we could declare in this way and pass parameter to base class in :base (parameters to base class constructor);
- so there is no need to declare in this way.
Any comments? Is my understanding correct?
[Code]
DerivedClassConstructor():base()
{
// derived class constructor implementation
}
[/Code]
thanks in advance,
George
George GeorgePosted Oct 31, 2008, 6:13 AM
Thanks Mamta,
I like your reply.
regards,
George
Mamta MPosted Oct 30, 2008, 11:37 PM
Hi George,
One of the aspects of good design is better readbility for a developer reading the code. Maybe it's not a big thing but it isn't trivial either.
Say, you have a derived class with four to six overloaded constructors. In addition, it is assumed that the default parameterless constructor also will be invoked when you create an object of the derived class. But when you have so many overloaded constructors, it might be difficult to remember that the parameterless constructor WILL be invoked anyway.
Taking one look at the derived class declaration with the explicitly invoked parameterless constructor (through base()) will definitely make it easier on the eye.
Regards,
Mamta
George GeorgePosted Oct 30, 2008, 8:38 AM
Hi Mamta,
Could you clarify why you think explicitly invoking base() is better design please?
regards,
George
Mamta MPosted Oct 30, 2008, 3:29 AM
Hi George,
As far as I know, you are perfectly right. The only reason that I can think of for explicitly invoking the constructor (in the manner as indicated in the code you have shown) is for better class design.
Regards,
Mamta