Search code examples
c++oopinheritancec++17abstraction

C++ Abstraction OOP (Inherit only some method to derived class)


Suppose i have a socket class:

class Socket{
public:
    ... Some Code ...
    Socket(int type){
         isServer = type;
        //some code
    }
    virtual void Send(string s);
    virtual void Send(string s, int clientID);
    ... Some Code ...
private:
    int isServer;
};

This is to be used both as a server and client.

Now I need to have 2 Derived classes:

class ClientSocket : public Socket{
public:
    ... Some Code ...
};

class ServerSocket : public Socket{
public:
    ... Some Code ...
};

What I want is that ClientSocket will only have access to Send(string) and server socket will only have access to Send(string, int)

I checked some other answer:

And that has a good idea of not using inheritance at all rather just encapsulate(Have a socket instance in server). But I want to know whether this can be done using Inheritance.


Solution

  • There is not absoulte way to doing such thing.

    But here my idea:

    create two class(like interface):

    first class is server socket sender:

    Class ServerSocketSender {
      public:
        virtual void Send(string s, int clientID);
    }
    

    second class is client socket sender:

    Class ClientSocketSender {
      public:
        virtual void Send(string s);
    }
    

    due to interface segregation principle i recommend you to do such thing it is not wise choice to combine two send method in one class and enable desire method in desire class.

    another trick that i saw many times but i dont know exactly if it's work in your case or not is something called SFINAE. with this trick i think you can achieve same thing but due to complexity i not recommend this approach.