Search code examples
c++classconstructorwxwidgets

Error when trying to copy variable in constructor of a class


I'm using wxWidgets, but I think this to my question there is no difference.

The problem is that I need to copy and keep in a different place the memory the socketConnect, when initialization the threadReadPacket in threadWaitConnection::Entry. I'm currently trying to pass this value by the constructor, but I can not.

Some returns error messages:

main.cpp:97:70: error: within this context
         threadReadPacket *thread = new threadReadPacket(socketConnect);
                                                                      ^
main.cpp:22:5: error:   initializing argument 1 of ‘threadReadPacket::threadReadPacket(wxSocketBase)’
     threadReadPacket(wxSocketBase setSocket) {
     ^

Code:

/* Thread */
// threadReadPacket
class threadReadPacket : public wxThread {
public:
    threadReadPacket(wxSocketBase setSocket) {
        socket = setSocket;
    };
    virtual ~threadReadPacket();

    virtual void *Entry();

private:
    wxSocketBase socket;
};

threadReadPacket::~threadReadPacket() {

}

threadReadPacket::ExitCode threadReadPacket::Entry() {
    /* [...]
    Lots and lots of lines of code
    [...] */
}

// threadWaitConnection
class threadWaitConnection : public wxThread {
public:
    threadWaitConnection(wxSocketServer *setSocket) {
        socket = setSocket;
    };
    virtual ~threadWaitConnection();

    virtual void *Entry();

private:
    wxSocketServer *socket;
};

threadWaitConnection::~threadWaitConnection() {

}

threadWaitConnection::ExitCode threadWaitConnection::Entry() {
    wxPrintf("Waiting for connection...\n");
    wxSocketBase socketConnect;
    socket->AcceptWith(socketConnect, true);

    if (socketConnect.Ok()) {
        wxPrintf("Success on connect\n");
        threadReadPacket *thread = new threadReadPacket(socketConnect);

        if (thread->Run() != wxTHREAD_NO_ERROR) {
            wxPrintf("Can't start thread!");
            return NULL;
        }
    } else {
        wxPrintf("Not connected\n");
        return NULL;
    }

    // Finish
    socketConnect.Close();

    return NULL;
}

Solution

  • Do not know if it was the most elegant solution, but it was the only one that worked. I copied the memory of the socket in the heap and passed her position to the constructor.

    That way I can store multiple socket and uses them way indepedent.