derrdji
derrdji

Reputation: 13321

What is wrong with this c++ typedef?

This is a piece of my code, I have more class like MathStudent, ArtStudent, etc. which inherits Student class. When I tried to compile, it says "forbids declaration of `vector' with no type," what is the problem here? thanks

class Student {
public:
    typedef vector<Student> Friends; // something wrong here?

    virtual unsigned int getId() = 0;

    //some more pure virtual functions...
};

Upvotes: 0

Views: 1657

Answers (4)

Michael Burr
Michael Burr

Reputation: 340316

One problem with the typedef is that class Student is an abstract class, so it cannot be default constructed, which is required for types that vectors can be composed of.

Another issue (say you removed the fact that class Student is abstract) might be that the class isn't fully defined. You can, in fact, declare a typedef for a vector<> with an incomplete class, but you wouldn't be able to actually use the typedef until the class was fully defined - except to declare pointers or references to the type.

In both a cases you may need to think about the class's overall design - you may want to have a vector<Student*> instead so the vector can hold any type of student (using pointers since it can't hold an actual abstract Student object). As others have mentioned using smart pointers (but not std::auto_ptr<>) would help with managing the lifetimes of object pointed to by the vector.

Upvotes: 6

tim
tim

Reputation: 632

You need to include the header for vector and consider the namespace.

Eg:

#include <vector>

using namespace std;

...rest of your code here...

should compile just fine.

Upvotes: 0

C. K. Young
C. K. Young

Reputation: 223123

Vectors store items by value, not by reference. If you want to be able to store MathStudent, ArtStudent, and the like, you should think about using a vector of (smart) pointers to Student instead:

typedef vector<shared_ptr<Student> > friends;

(where shared_ptr is either std::tr1::shared_ptr or boost::shared_ptr, depending on whether your C++ system supports TR1.)

Upvotes: 3

John Zwinck
John Zwinck

Reputation: 249404

You can't use a class which is not yet defined. You could however use a pointer to that class.

Your specific error right now is probably that you forgot to #include <vector> or do using namespace std;. But as soon as you solve that, you'll need my first advice.

Upvotes: 10

Related Questions