I have a question related to the default constructor in C++.
Following are the classes and the code:
class Name
{
public:
Name(string name);
private:
m_name;
}
class DataBase
{
public:
DataBase();
void addToDB(string name);
Name* getPtrToName(string name);
private:
Name m_Name[10];
int NoOfEntries;
}
Now I am trying to create an object of class DataBase and add new entries to the database.
/*
* Name.cpp
*/
Name::Name(string name) //overloaded constructor
{
m_name = name;
}
/*
* DataBase.cpp
*/
DataBase::addToDB(string name) // add entries to the database
{
Name newEntryToDB(name);
m_Name[NoOfEntries] = newEntryToDB;
NoOfEntries++;
}
DataBase::DataBase() // gives an error stating no matching call for function Name::Name()
{
NoOfEntries = 0;
}
The error "no matching call for function Name::Name() "
Now I understand that I can simply define a default constructor in the Name.cpp and resolve the compilation error. But isn't the default constructor invoked by the compiler automatically? This should possibly avoid the trigger of the error.
Is there any other way to resolve this error apart from defining the default constructor in Name.cpp?
std::vectorinstead. -- OR -- Actually define the default constructor which will initialize Name to some "dummy" or "null" value. How exactly this dummy value is defined is mostly unimportant if you only access up toNoOfEntriesentries of your array.NoOfEntrieswill be used to restrict the value of Database. I avoided adding here to simplify the code. :)