Should i definitely have a constructor in a derived class?
My problem is like this. I have a XMLUtility class
public class XmlUtility
{
protected string FilePath;
protected s开发者_运维技巧tring XMLFileName;
protected XmlDocument SettingsFile;
public XmlUtility(string inFilePath, string inXMLFileName)
{
FilePath = inFilePath;
XMLFileName = inXMLFileName;
if (isFilePresent() == false)
{
createXMLFile();
}
else
{
SettingsFile = new XmlDocument();
SettingsFile.Load(FilePath + "\\" + XMLFileName);
}
}
and a
public bool isFilePresent()
{
return File.Exists(FilePath + "\\" + XMLFileName) ? true : false;
}
and other basic functions such as addSetting, removeSetting, checkSettingExists etc. This class provides functionality for very basic xml settings file.
So now i need a bit more advanced handling of settings. So i created another class and derived it from the XMLUtility class.
public class KeyPairingXML : XmlUtility
{
}
So my initial thought was i don't need to have a constructor for this class as it will call the base classes constructor. But i was wrong.
public KeyPairingXML(string inFilePath, string inXMLFileName) : base(inFilePath, inXMLFileName)
{
}
My question is whether the code above correct? Do i need to write the whole checking process inside this constructor as well or will that be handled by the base class's constructor? Just an empty code block is correct?
Not sure which language you are using, but for most (such as Java or C#) you can ommit defining a constructor in a derived type if:
- The base class does not define a constructor (therefore it has an implicit default constructor)
- The base class defines a no-argument constructor. In this case it can have other constructors and it won't change things
However, your base class only defined a non-default constructor so you need to redefine it in the derived class. The following code you have is correct:
public KeyPairingXML(string inFilePath, string inXMLFileName)
: base(inFilePath, inXMLFileName) {
}
You should also be able to call the public method on the base class. Are you seeing any errors/warnings?
精彩评论