Sista
Sista

Reputation: 887

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.

Upvotes: 2

Views: 6627

Answers (3)

Ben Voigt
Ben Voigt

Reputation: 283614

section [class.ctor] of the standard says (wording from draft n3242):

A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted (8.4). An implicitly-declared default constructor is an inline public member of its class.

You have a user-declared constructor:

netlist(const netlist &);

thus the compiler does not provide a default constructor.

Upvotes: 0

Mahesh
Mahesh

Reputation: 34605

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

Upvotes: 6

flight
flight

Reputation: 7272

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.

Upvotes: 6

Related Questions