I have a problem with protected constructor of base class which is used in private function of derived class:
Base class:
class Socket
{
public:
virtual ~Socket();
// Constructors :
Socket();
protected:
Socket(SOCKET& s);
};
Derived class:
class Server : public Socket
{
public:
Server();
~Server();
private:
int ServerLoop();
};
I try to create Socket object in ServerLoop function
SOCKET client_sock = accept( m_socket, ( sockaddr* )&client_addr, &size );
Socket* Client = new Socket( client_sock );
^^^^^^
But i get this error:
error C2248: 'NET_SOCKETS::Socket::Socket' : cannot access protected member
declared in class 'NET_SOCKETS::Socket'
in the line over the ^^^^. What is causing that error?
It was a bit surprising to me since it's a constructor, but it's the same principle as for non-static member functions. Protected base class non-static member functions can only be called on instances of the derived class (or derived from that class again), because otherwise one could gain access to protected features of any derived class simply by deriving from the base.
A workaround is to do exactly that, deriving a class specifically for the purpose of calling the protected base class constructor.
Eg, replace
Socket* Client = new Socket( client_sock );
with
struct DSocket: Socket
{
DSocket( SOCKET const socket )
: Socket( socket )
{}
};
Socket* Client = new DSocket( client_sock );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.