views:

2121

answers:

2

Socket has a constructor that takes a winsock SOCKET as parameter and stores it in a private variable:

Socket::Socket(SOCKET s) {
    this->s = s;
}

I'm trying to make an abstract class "GameSocket" that will parse data from my Socket class:

class GameSocket : public Socket {

protected:

    void ParseData(unsigned char* data, int size);

};

Next to these classes, I have a "Server" class that creates new sockets when needed:

GameSocket* Server::Accept() {

    SOCKET a = accept(s, 0, 0);
    if(a==SOCKET_ERROR) {
     return 0;
    }
    else {
     return new GameSocket(a);
    }

}

However, this gives me an error on the last "else":

error C2664: 'GameSocket::GameSocket' : cannot convert parameter 1 from 'SOCKET' to 'const GameSocket &'

I must be missing something with constructors when dealing with derived classes...

Don't go too hard on me, I'm relatively new to C++ and OOP

+6  A: 

Add in a constructor for GameSocket

class GameSocket : public Socket {

public:

    // you need to add
    GameSocket(SOCKET s) : Socket(s) {}

protected:

    void ParseData(unsigned char* data, int size);

};
David Allan Finch
Shouldn't the constructor be in the public: block of the class?
Laserallan
oh yes - will correct it - thanks
David Allan Finch
One of those C++ annoyances: constructors not inheritable. I am sure there are good reasons for it, but I want the public copnstructors to be inherited when I don't provide my own, damn it!
Arkadiy
+2  A: 

The construcotr for GameSocket must receive a SOCKET parameter and then pass it to the Socket base class in the initializer list:

class GameSocket : public Socket {
public:
    GameSocket(SOCKET s) : Socket(s) {}
    ...
};

Is there a reason why GameSocket must derive from Socket instead of holding a reference to the Socket? GameSocket is (or should be) managing socket state and serialization while the low level socket interface is contained in the Socket class. Your Server class could create instances of the Socket class and then pass a pointer to a GameSocket class for managing them.

class GameSocket {
public:
    GameSocket(Socket *s) : s_(s) {}
    ~GameSocket() {
        s_->close();
        delete s_;
    }
    ...
private:
    Socket *s_;
};

GameSocket* Server::Accept() {
    // accept function added to Socket class
    Socket *newSocket = serverSocket->accept();
    // create GameSocket with newly opened Socket
    return newSocket ? new GameSocket(newSocket) : NULL;
}
Judge Maygarden
Good point. I hope the asker (Daniel) will consider choosing composition over inheritance. The composition option seems to get overlooked in cases like these.
que que