Malcolm Malcolm - 1 year ago 84
C++ Question

Linked List...declaration incompatible with the protoype

Hey guys so I am getting this error when I am trying to create this function for my linked list class. The function I am having problems with is my search function. I haven't even started creating the function yet but the error I am receiving is in the declaration of the search function. On line 38 under NodePtr it says it is undefined and under search it says Error: declaration incompatible with "LinkedList::NodePtr (declared on line 17). The code is below. Any help appreciated.

// LinkedListProject.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <iostream>
#include <list>
using namespace std;
class LinkedList {
struct Node {
int data;
Node* link;
typedef Node* NodePtr;
//NodePtr head = new Node;
void head_insert(NodePtr& head, int the_number);
NodePtr search(NodePtr head, int target);

int main()
LinkedList obj;
//obj.head->data = 3;
//obj.head->link = NULL;
return 0;

void LinkedList::head_insert(NodePtr& head, int the_number) {
NodePtr temp_ptr = new Node;
temp_ptr->data = the_number;
temp_ptr->link = head;
head = temp_ptr;

NodePtr LinkedList::search(NodePtr head, int target)
return NodePtr();

Answer Source

NodePtr is a name scoped to you class. In order to use it outside of the class you need LinkedList::NodePtr. So you have to change

NodePtr LinkedList::search(NodePtr head, int target)


LinkedList::NodePtr LinkedList::search(NodePtr head, int target)

Now you may ask, "But wait, I didn't need it in search, what gives?", and the answer to that is after you do


The class name is injected into the rest of the scope of the function. Because of this we do not need to explicitly qualify any name that is scoped to the class.