Singly linked class, why doesnt it work.

So, I made a custom singly linked class program using templates and I want to overload the operator * with an int to copy each element in the list 'int=x' times. I am wondering why doesnt it work or rather what should I return.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Lista<T> & operator*(int number) const
    {
        Lista<T> temp;
        temp=*this;
        int i=0;
        int f=0;
        int w = this->size(); // size() - method returning number of elements in the list
        for(i;i<w;i++)
         {
            int n;
            for(n=0;n<number-1;n++){
            temp.put_index(f, this->given(i)->info); // put_index - function inserting an element inside the list at a given index; given(i)->info - getting the element from a given index
            std::cout << temp << std::endl; // Just to see the outcome
            std::cout << *this << std::endl;//  -||-
                        }
            f=f+n+1;
         }
    return temp;
    }


Now lets say I have a list : 1 2
After all the calculations std;:cout << temp gives me 1 1 2 2 just how its supposed to
std::cout << *this gives me 1 2 which is also correct

but when i try to return this 1 1 2 2 it gives me some random numbers that I dont know where they come from.
Do you have any idea on whats wrong?

Greetings.
Last edited on
temp is a local object that will no longer exist when operator* ends. Just return a Lista<T> instead of a reference.
After 3 hours of scratching my head it appeared that I had to remove the "&" from the "Lista<T> & operator*(int number) const". Mind explaining to me why it has to be this way?

@up : i know it wont exist, I want it to work this way. I return Lista<T> in the *= case.
Last edited on
Peter is correct, and the issue he pointed out answers your next question as well. When you return List<T> &, you are returning a reference to an existing list object. It's very similar to returning a pointer. Imagine if your method returned List<T> *, and you decided to "return &temp;". What would you expect to happen? Your return value points to memory that has already been cleaned up, so now can be anything at all. Same case above - the 'temp' variable goes out of scope when the function ends, but you are returning it anyway, so it's contents are undefined.
Topic archived. No new replies allowed.