This is supposed to be very basic.
Layout:
class handler {
public:
handler(Connection *conn) { connection = conn; }
virtual void handle() = 0;
};
class http_status : public handler {
public:
http_status(Connection *conn) : handler(conn) { }
void handle();
};
class http_photoserver : public handler {
public:
http_photoserver(Connection *conn) : handler(conn) { }
void handle();
};
Code:
void pick_and_handle() {
if (connection->http_header.uri_str != "/") {
http_photoserver handler(connection);
} else {
http_status handler(connection);
}
handler.handle();
}
This gives an error:
../handler.cpp:51:10: error: expected unqualified-id before ‘.’ token
I'm guessing because compiler doesn't know what handler is cause object is created inside an if statement. I need to pick a handler based on a condition, how do I do that?
Obviously this code works:
if (connection->http_header.uri_str != "/") {
http_photoserver handler(connection);
handler.handle();
} else {
http_status handler(connection);
handler.handle();
}
But doesn't look very sexy! Is it really the only way in c++?
Use a pointer so you get polymorphic behavior:
auto_ptr<handler> theHandler = (connection->http_header.uri_str != "/") ?
new http_photoserver(connection) :
new http_status(connection);
theHandler->handle();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With