Leslie Zhou
Leslie Zhou

Reputation: 361

C++ error: definition of implicitly-declared

I'm writing this linked list program with C++

When I test the program, I got the error

linkedlist.cpp:5:24: error: definition of implicitly-declared 'constexpr LinkedList::LinkedList()' LinkedList::LinkedList(){

Here's the code

linkedlist.h file:

#include "node.h"
using namespace std;

class LinkedList {
  Node * head = nullptr;
  int length = 0;
public:
  void add( int );
  bool remove( int );
  int find( int );
  int count( int );
  int at( int );
  int len();
};

linkedlist.cpp file:

#include "linkedlist.h"
#include <iostream>
using namespace std;

LinkedList::LinkedList(){
  length = 0;
  head = NULL;
}
/*and all the methods below*/

please help.

Upvotes: 26

Views: 79845

Answers (3)

JOSEPH BENOY
JOSEPH BENOY

Reputation: 169

You should declare the constructor inside the class inorder to define the cunstructor outside the class. Otherwise you should define it inside the class itself.Your class should look like this.

            #include "node.h"
            using namespace std;
            class LinkedList {
              Node * head = nullptr;
              int length = 0;
            public:
              LinkedList();
              void add( int );
              bool remove( int );
              int find( int );
              int count( int );
              int at( int );
              int len();
            };

Upvotes: 4

Divya Barvekar
Divya Barvekar

Reputation: 1

To define constructor outside the class you need to declare it first in public specifier then define it outside the class.

#include "node.h"
using namespace std;

class LinkedList {
  Node * head = nullptr;
  int length = 0;
public:
  LinkedList();
  void add( int );
  bool remove( int );
  int find( int );
  int count( int );
  int at( int );
  int len();
};


LinkedList::LinkedList(){
  length = 0;
  head = NULL;
}

Upvotes: 0

CinCout
CinCout

Reputation: 9619

Declare the parameterless constructor in the header file:

class LinkedList {
{
....
public:
    LinkedList();
    ....
}

You are defining it in the .cpp file without actually declaring it. But since the compiler provides such a constructor by default (if no other constructor is declared), the error clearly states that you are trying to define an implicitly-declared constructor.

Upvotes: 35

Related Questions