0

I'm trying to write a linked-list using class and I want it to have a specific format.

For example if I have three data called p1,p2 and p3 and a linked-list called list; I want to put them in order like blow.

list.insert(p1).insert(p2).insert(p3);

I tried to return the object, but didn't work. Here's my code.


#include<iostream>

using namespace std;

class linked_list {
public:
    int *head;
    linked_list();
    ~linked_list();
    linked_list  insert(int data);

};

linked_list::linked_list()
{
    head = NULL;

}
linked_list::~linked_list()
{
    int *temp;
    int *de;
    for (temp = head;temp != NULL;) {
        de = temp->next;
        delete temp;
        temp = de;
    }
    delete temp;
    //delete de;

}
linked_list  linked_list::insert(int data)
{
    int *temp;
    temp = new int;
    *temp = data;
    temp->next = NULL;
    if (head == NULL) {
        head = temp;
    }
    else {
        int* node = head;
        while (node->next != NULL) {
            node = node->next;
        }
        node->next = temp;
    //  delete node;
    }
    //delete temp;

    return *this;


}
int main(){
    linked_list l1;
    int p1,p2,p3;
    l1.insert(p1).insert(p2).insert(p3);
    return 0;}


Lily
  • 142
  • 9
  • There are multiple fundamental bugs with the shown code. Not Rule of 3 compliant. Improper usage (no usage whatsoever) of references. What you really need is to spend more time [with a good C++ textbook](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and learn fundamental C++ concepts that must be used here. This is beyond the scope of a quick answer on stackoverflow.com. – Sam Varshavchik Apr 11 '20 at 14:14
  • To allow correct `list.insert(p1).insert(p2).insert(p3);` you have to return reference. – Jarod42 Apr 11 '20 at 14:16
  • `int* node = head; while (node->next != NULL) {`. Ouch... – Jarod42 Apr 11 '20 at 14:18
  • Where should that `next` on a `int*` come from? You need to create a class to represent nodes. – Lukas-T Apr 11 '20 at 14:56

1 Answers1

0

@Jarod42 got your answer, despite all the buggy things around, what you want is something like this.

The function you want to chain must return a reference to your current object instance.

Here is a Foo class that change its _data member and chain multiple time.

#include <iostream>

class Foo
{
private:
    int _data;

public:
    Foo(int data) : _data(data) {}
    ~Foo()
    {
    }

    // change the value of data then return a reference to the current Foo instance
    Foo &changeData(int a)
    {
        _data = a;
        return *this;
    }

    void printData()
    {
        std::cout << _data << std::endl;
    }
};

int main()
{
    Foo f(1);

    f.changeData(2).changeData(3);
    f.printData();
}

Note that I'm returning Foo& from the function I'm chaining, that's the little trick that is missing from yours.

Hope it helped you :)

MiniClem
  • 20
  • 2