Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope issue while creating objects inside if statement if C++

Tags:

c++

scope

object

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++?

like image 314
BadMondays Avatar asked Jun 27 '26 06:06

BadMondays


1 Answers

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();
like image 85
Ernest Friedman-Hill Avatar answered Jun 28 '26 18:06

Ernest Friedman-Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!