C ++ classes - declaring a constructor in a derived class

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

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

      

I am trying to create a GameSocket class 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 as 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 in the last "else":

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

      

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

Don't bother me too much, I'm relatively new to C ++ and OOP

+1


source to share


2 answers


Add to 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);

};

      

+6




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

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

      



Is there a reason the GameSocket should be pulled from the Socket instead of referencing the Socket? GameSocket (or should be) manages socket state and serialization, and the low-level socket interface is contained in the Socket class. Your server class can create instances of the Socket class and then pass a pointer to the GameSocket class to manipulate 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;
}

      

+2


source







All Articles