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?
But isn't the default constructor invoked by the compiler automatically?
No it is not. As soon as you provide your own constructor the compiler will no longer provide a default constructor. You will either have to make one or you could just use
Name() = default;
In the class declaration in the header file to declare a default constructor.
Alternatively you could switch to using a std::vector
which will allow you to have an "array" but allow you to add to it one object at a time.