macabeus
macabeus

Reputation: 4592

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;
}

Upvotes: 0

Views: 103

Answers (2)

macabeus
macabeus

Reputation: 4592

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.

Upvotes: 0

egur
egur

Reputation: 7970

See this:

/usr/include/wx-3.0-unofficial/wx/socket.h:303:29: error: ‘wxSocketBase::wxSocketBase(const wxSocketBase&)’ is private
     wxDECLARE_NO_COPY_CLASS(wxSocketBase);

This means the socket object can't be copied since it's copy constructor is private.

You code should keep a reference to the socket object instead (or a pointer).

Upvotes: 1

Related Questions