Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come I can use a forward-declared class in a std::vector?

Tags:

c++

I thought that you could only create a reference or pointer member to a forward-declared class. However, I was surprised to discover this works:

#include <vector>

struct Donkey;

struct Cage
{
    std::vector<Donkey> donkeys;
};

struct Donkey
{
};

int main()
{
    Cage c;
}

http://ideone.com/EP0zKR

How come std::vector can be defined with a forward-declared class? Is this standard?

like image 704
Neil Kirk Avatar asked Dec 12 '25 16:12

Neil Kirk


1 Answers

Actually, you can't.

Just because your program compiles (which is down to facts of the underlying implementation) does not mean it is valid.

There are times other than declaring a T* or a T& at which you may use a forward declaration; it's just that this is not one of them.

like image 131
Lightness Races in Orbit Avatar answered Dec 15 '25 08:12

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!