Reputation: 269
My goal here was, instead of placing all methods in ServerInterface(superclass), i wanted to place the methods in child classes to organize the code better.
class ServerInterface
{
public:
Router* router = new Router();
Client* client = new Client();
ServerInterface() {
} //Creates new Router and Client instance
};
class Router : public ServerInterface
{
public:
Router() {}
void randomRouterFunction() {}
};
class Client : public ServerInterface
{
public:
Client() {}
virtual void randomClientFunction() {};
};
class ProductionServer : public ServerInterface
{
public:
ProductionServer() {}
};
int main() {
ProductionServer* productionServer = new ProductionServer();
productionServer->router->randomRouterFunction(); //causes it to not debug
return 0;
}
In my situation I am only allowed to access to ProductionServer
which has to inherit from ServerInterface
in my code.
So instead of calling productionServer->randomRouterFunction()
or productionServer->randomClientFunction()
, i wanted to be able to call productionServer->Router->randomRouterFunction()
etc
Even though intellisense tells me that it's all working fine, trying to run my code i recieve
main:289:20: error: 'class ProductionServer' has no member named 'router'
productionServer->router->randomRouterFunction();
Is this even feasible to accomplish? The reason for thinking it may not work is cause the superclass creates a member of Router which is the child class, and then the router child class creates another superclass since it inherits it, which then creats another router child class in the superclass.... and it would be an infinite loop? XD
ps. The randomFunction() could be any method, just used as an example.
Upvotes: 0
Views: 96
Reputation: 117298
The problem is with the design. You can compile this but when you create a ProductionServer
it will instantiate a ServerInterface
which will create a Router
and a Client
and those will both also instantiate a ServerInterface
that will create a Router
and a Client
and so on - until you get a stack overflow.
In order to get this in some working condition, you need to add something that breaks that cycle so that it doesn't instantiate Router
s and Client
s endlessly.
Upvotes: 1