struct forward declaration fails compile

Tony The Lion picture Tony The Lion · Feb 17, 2011 · Viewed 19.2k times · Source

I have the following code, but the compiler says sender_wrapper is undefined, even though I forward declared it. Can I not do a forward declare of a struct? (compiled with VS2003)

struct send_wrapper;

struct IPSend
{
    IPSend::IPSend(const send_wrapper& sender) : _sender(sender) {}

    void IPSend::operator()(const std::string& msg)
    {           
        if (!msg.empty())
            _sender.send(msg);
    }

    send_wrapper _sender; //error C2079: 'IPSend::_sender' uses undefined struct 'send_wrapper'

};

struct send_wrapper 
{
std::auto_ptr<tcp_server> server;

};

Answer

Oliver Charlesworth picture Oliver Charlesworth · Feb 17, 2011

Forward declarations of types can only be used to resolve declarations involving pointers and references to that type.

Before the type has been fully defined, the compiler does not know anything about the type; e.g. what members it has, or how big it is. Therefore, you cannot use it as a by-value member of your struct, because the compiler wouldn't know how big to make it, or whether its constructors and destructor are public. On the other hand, you are free to do something like send_wrapper *_p_sender;, because pointers to structs are always the same size. But you still wouldn't be able to access its member functions, etc.