0

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?

2
  • Well, your array always contains exactly 10 elements. How would you want the array to be initialized in the beginning? If you want it to be dynamically-sized (i.e. empty in the beginning of the lifetime of a DataBase object), use a std::vector instead. -- 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 to NoOfEntries entries of your array. Commented Nov 3, 2016 at 12:29
  • @leemes - exactly!! the NoOfEntries will be used to restrict the value of Database. I avoided adding here to simplify the code. :) Commented Nov 3, 2016 at 12:39

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.