L
L
LittleBuster2016-02-02 10:13:56
OOP
LittleBuster, 2016-02-02 10:13:56

C++ interface inheritance?

Please help me figure out how to correctly inherit an interface from another class to the interface of a new class, so that the new interface knows the functions of both the parent and the child, but the compiler would not give errors "You can not call the constructor of the abstract class Server" or errors like "The class does not have such a method ".
I tried to create some new interface class IMainServer: public IServer, public ITcpSocket but then go() gives errors about the impossibility of converting Server to it.

#include <memory>
#include <iostream>

using namespace std;

/* Interfaces */
class ITcpSocket
{
public:
    virtual void start(void) = 0;
};


class IServer: public ITcpSocket
{
public:
    virtual void load(void) = 0;
};


/* Classes */
class TcpSocket: public ITcpSocket
{
public:
    void start(void)
    {
        cout << "start" << endl;
    }
};


class Server: public IServer, public TcpSocket
{
public:
    void load(void)
    {
        cout << "load" << endl;
    }
};


void go(shared_ptr<IServer> server)
{
    server->start();
    server->load();
}

int main()
{
    auto server = make_shared<Server>();
    go(server);

    return 0;
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
MiiNiPaa, 2016-02-02
@LittleBuster

So you have diamond-shaped inheritance.
TcpSocket::ITcpSocket::start is defined, but IServer::ITcpSocket::start is not.
Here are the problems. You can solve them by inheriting from interfaces virtually.

P
Peter, 2016-02-02
@petermzg

So the compiler is right. You cannot instantiate an abstract class.
Define all the methods that are in the interface and everything will work.

class TcpSocket: public ITcpSocket
{
public:
    void start(void)
    {
        cout << "start" << endl;
    }
   void load(void)
   {
   }
};

R
res2001, 2016-02-02
@res2001

Go() is passed a pointer to IServer, but iServer does not have a start method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question