user1019880
user1019880

Reputation: 41

C++ Object references in loop cycle

I'm trying to create different objects of the same type using a loop, and then storing a pointer to each specific object in a linked list. The problem is, each time an object is instanciate, its pointer return the same memory adress, wich doesn't allow me to differentiate each individual object in that list.

Any solution to that? Thanks

I have a function with the following:

    Data dt(10,10,2010);
int p=0;
ifstream fx;
fx.open("utilizadores.txt",ifstream::in);
if(!fx)
{cout << "FX. nao existe!" <<endl;}
string linha;
string nLugar;
int iD=1;

while(!fx.eof())
{
    getline(fx,linha,'\n');
    Utilizador* user;
    if(linha.find(',')==-1 && linha.size()>1)
    {
        cout<<"Entrou no vector"<<endl;
        string nlugar(linha.substr(0, linha.size()));
        nLugar=nlugar;

    }

      else
    {
        int inic=0;
        int pos=linha.find(',',inic);
        string nick(linha.substr(inic,pos-inic));
        pos++;
        inic=pos;
        pos=linha.find(',',inic);
        string email(linha.substr(inic,pos-inic));
        user=new Utilizador(dt,iD,nick,email);
        cout<<&user<<endl;
        cout<<user->clone()<<endl;
        }
    fx.close();
    }

The linked list is declared in the class statement

Upvotes: 0

Views: 313

Answers (3)

Adam
Adam

Reputation: 9

"&user" return address of pointer, that contains references to objects.

Upvotes: 1

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

This line

cout<<&user<<endl;

prints the address of a pointer to an object. user is itself a pointer to the object you're creating. To print the address of your object, you meant to write

cout<<user<<endl;

Although it'll be a new object each time, the variable user is always in the same place. You can add the value of user to your list, and it will indeed be different each time.

Upvotes: 2

Alex F
Alex F

Reputation: 43311

cout<<&user<<endl;

should be:

cout<<user<<endl;

&user is address of local variable Utilizador*, which remains the same. user variable value itself is the pointer you need, and it should be different on every iteration.

Upvotes: 3

Related Questions