Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default constructor C++ error

I require help with respect to class construction. In my class, I have used a copy constructor and operator= to prevent the compiler from creating them. In my main program, when I try to create an instance of the class, I get an error saying "No default constructor exists for the class".

What could be the problem?

This is a snippet of my code.

class netlist {
    netlist(const netlist &);
    netlist &operator=(const netlist &);
    std::map<std::string, net *> nets_;
}; // class netlist

In my main function I am using:

netlist nl;

This is where I get the error. I am providing the copy constructor declaration, so they should not be a problem.

I would appreciate any help with this. Thanks in advance.

like image 621
Sista Avatar asked Nov 28 '25 09:11

Sista


2 Answers

There are two problems with the code -

  1. class members are private by default.
  2. "I get an error saying "No default constructor exists for the class" ".

Because if any kind of constructor is provided as a part of class declaration( netlist class has a copy constructor in this case), default constructor( i.e., constructor with no arguments ) is not provided by compiler.

netlist nl;  // And this invokes call to the default constructor and so
             // the error

netlist.h

class netlist {

public: // Added
    netlist(); // This just a declaration. Should provide the definition.
    netlist(const netlist &);
    netlist &operator=(const netlist &);
    std::map<std::string, net *> nets_;
}; // class netlist

netlist.cpp

netlist::netlist()
{
       // .....
}

// Other definitions
like image 164
Mahesh Avatar answered Nov 29 '25 23:11

Mahesh


When you create the netlist you are not passing any arguments to the constructor which means you are calling a default constructor. However you didn't define a default constructor. You only created a constructor taking a different netlist as a parameter (the copy constructor) here:

netlist(const netlist &);

You should define a default constructor like this:

netlist();

Note that had you not defined any constructor, the compiler would have added default ones but since you added the copy constructor, you have to define all of them yourself.

like image 32
flight Avatar answered Nov 29 '25 23:11

flight