Answer the question
In order to leave comments, you need to log in
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
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.
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)
{
}
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question