I have a base class Character which has several classes deriving from it. The base class has various fields and methods.
All of my derived classes use the same base class constructor, but if I don’t redefine the constructor in my derived classes I get the error:
Error: Class “child class” doesn’t contain a constructor which takes this number of arguments
I don’t want to redefine the constructor in every derived class because if the constructor changes, I have to change it in every single class which, forgive any misunderstanding, goes against the idea of only writing code once?
You do have to redeclare constructors, because they’re effectively not inherited. It makes sense if you think of constructors as being a bit like static methods in some respects.
In particular, you wouldn’t want all constructors to be automatically inherited – after all, that would mean that every class would have a parameterless constructor, as
objectitself does.If you just want to call the base class constructor though, you don’t need to write any code in the body of the constructor – just pass the arguments up to the base class as per Waleed’s post.
If your base class starts requiring more information, it’s natural that you should have to change all derived classes – and indeed anything calling the constructors of those classes – because they have to provide the information. I know it can seem like a pain, but it’s just a natural consequence of what constructors do.