2

I am trying to overload the << operator to be an "insert_first operator" for a double linked list. This should be a simple procedure, and I have overloaded operators before, but I am stuck on this one. I am trying to overload it as:

DLList & DLList::operator << (const int value ) 
{
    insert_first(value);
}

My .h file seems fine, and is similar to other ones online:

#ifndef DLLIST_H
#define DLLISH_H

#include <stdio.h>
#include <iostream>

class ListNode {
public:
    int value; 

    ListNode * next;
    ListNode * prev;

    static int node_count;

    ListNode() {
        node_count++;
    }

    ~ListNode() {
        node_count--;
    }

    static void print_node_count() {
        std::cout << "Node Count: " << node_count << std::endl;
    }
};

class DLList {
private:
    ListNode * head;
public:
    DLList();
    ~DLList();

    void print_list();
    void print_list( std::string list_name );
    void insert_first( int value );

    bool remove( int value );
    void concat_list( DLList * list_to_add );

    DLList & operator << (const int value );
};

and my insert_first function also seems to be working fine:

void DLList::insert_first( int value ) 
{
    ListNode * n = new ListNode();

    n->value = value;
    n->next = head->next;
    n->prev = head;

    head->next = n;
    n->next->prev = n;    
}

The error I'm receiving is a segfault. Any ideas or comments would be much appreciated.

5
  • 2
    You are not returning anything from operator << when you told the compiler it would return a DLList&. Commented Dec 17, 2015 at 20:35
  • You don't return *this meaning operator<< has undefined behavior (no return type in a non-void function) Commented Dec 17, 2015 at 20:36
  • I see it now, thank you Commented Dec 17, 2015 at 20:39
  • why does "insert_first" actually insert it after head ? Commented Dec 18, 2015 at 1:17
  • that's just the way it's written. head doesn't store a value, it's just there for convenience. Commented Dec 19, 2015 at 1:45

1 Answer 1

1

ok, so as the comments suggested, I needed to return something from the operator like

DLList & DLList::operator << (const int value ) 
{
insert_first(value);
return *this; 
}
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.