Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling C++ when two classes refer to one another

I am trying to write a simple wrapper around a connection pointer that will return it to the pool when the wrapper is destroyed, but it wont compile because the ConnectionPool and AutoConn need each other to be declared.

I tried to use forward deceleration but it didn't work. How do I solve this? (using g++)

class Connection {};

class ConnectionPool
{
    Connection *m_c;
public: 
    AutoConn getConn()
    {
        return AutoConn(this, m_c); // by value
    }

    void releaseConnection(Connection *c)
    {
    }
};

class AutoConn
{
    ConnectionPool* m_pool;
    Connection *m_connection;
public:
    AutoConn(ConnectionPool* pool, Connection *c) : m_pool(pool), m_connection(c) {}
    ~AutoConn()
    {
        m_pool->releaseConnection(m_connection);
    }
};
like image 537
Omry Yadan Avatar asked Mar 15 '10 13:03

Omry Yadan


3 Answers

A combination of forward declaration and separation of declaration from definition of members with circular dependencies works. For example:

class Connection {};
class ConnectionPool ;

class AutoConn
{

    ConnectionPool* m_pool;
    Connection *m_connection;
public:
    AutoConn(ConnectionPool* pool, Connection *c) : m_pool(pool), m_connection(c) {}
    ~AutoConn() ;  // Not defined here because it accesses unknown members of class Connection
} ;

class ConnectionPool
{
    Connection *m_c;
public: 
    AutoConn getConn()
    {
        return AutoConn(this, m_c); // by value
    }

    void releaseConnection(Connection *c)
    {
    }
};

// Definition of destructor with class Connection member dependencies.
AutoConn::~AutoConn()
{
    m_pool->releaseConnection(m_connection);
}
like image 160
Clifford Avatar answered Sep 21 '22 03:09

Clifford


Use forward declaration:

class Connection {};

class ConnectionPool; //<<<<<<<<<<<<<<<forward declaration

class AutoConn {
//definitions
};

class ConnectionPool {
//definitions
};
like image 31
sharptooth Avatar answered Sep 20 '22 03:09

sharptooth


implement the functions after the point where the classes are defined

like image 37
stefaanv Avatar answered Sep 20 '22 03:09

stefaanv