Dann
Dann

Reputation: 65

forward declaration on c++ with a list inside

I have two clases Pet and Person

Here is the Person.h:

#ifndef PERSON_H
#define PERSON_H
#include <list>

class Pet;

class Person
{
public:
    Person();
    Person(const char* name);
    Person(const Person& orig);
    virtual ~Person();

    bool adopt(Pet& newPet);
    void feedPets();

private:
    char* name_;
    std::list<Pet> pets_;
};

#endif  

And here is the Pet.h

#ifndef PET_H
#define PET_H
#include <list>
#include "Animal.h"

class Person;

class Pet : public Animal
{
public:
    Pet();
    Pet(const Pet& orig);
    virtual ~Pet();
    std::list<Pet> multiply(Pet& pet);

private:
    std::string name_;
    Person* owner_;
};

#endif

The problem that i have is this:

/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/list.tcc:129: error: invalid use of undefined type `struct Pet'

Person.h:13: error: forward declaration of `struct Pet'

I fixed trying to put this std::list<Pet>* pets_; but when i tried to call list functions always have a link problem. My question is how a have to include a list inside a class that contains objects from another class.

Upvotes: 1

Views: 1015

Answers (1)

The standard requires that, except where explicitly stated, you use complete types with the library templates. This basically inhibits your design (where each object maintains by value a list of the other type).

You can work around this by using [smart] pointers (either a pointer to the container or container of pointers).

Upvotes: 4

Related Questions