Niklas Niklas - 1 year ago 90
C++ Question

std:: list, can't access object

I'm new to cpp and want to learn about list.
When I run my program it compiles fine but I don't get the result
I'm expecting.

This gives me the output

Legs: 0 Name:

It should be

Legs 4 Name: dog

Can any one see the problem?

As in the comment section, I have tried for over an hour and get get this to work, can't see the problem.

Header file

using namespace std;

#ifndef ANIMAL_H
#define ANIMAL_H

class Animal {
Animal(const Animal& orig);
virtual ~Animal();

int _Legs;
void SetName(string name);
string GetName();
string _Name;

#endif /* ANIMAL_H */


Animal::Animal() {

Animal::Animal(const Animal& orig) {

Animal::~Animal() {

string Animal::GetName(){return _Name;}

void Animal::SetName(string name){_Name = name;};

Main file

void List()

std::list<Animal> animal_list;

Animal temp;

temp = Animal();
temp._Legs = 4;

for(std::list<Animal>::iterator list_iter = animal_list.begin();
list_iter != animal_list.end(); list_iter++)
std::cout<< "Legs:" << list_iter->_Legs << " Name: " << list_iter->GetName() << endl;


int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)

return 0;

Answer Source

The reason you have nothing is your copy constructor is incorrect. You make a copy of temp when you add it into the list and it is this copy that you are accessing.

You have

Animal::Animal(const Animal& orig) {

Which means when you make a copy, all the members of the class are default initialized and nothing else happens.

The simplest solution is to just get rid of it and let the compiler provided default copy constructor do the copy for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download