Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do these two functions defined in the same class manage to call each other without forward declaration?

For the time I'm learning to code with boost/asio. Many code samples make use of the combination of async_accept and bind. In the server code , i come across some thing like this:

class Tcp_server
{
public:
    Tcp_server()
    {

    }
    void start_accept(int a)
    {
        if(a>0)
        {
            cout<<a<<endl;
            handle_accept(a-1);
        }

    }

    void handle_accept(int a)
    {
        if(a>0)
        {
            cout<<a<<endl;
            start_accept(a-1);
        }

    }
};

If i make an instance of Tcp_server and call either handle_accept or start accept, it works. But if I drop the Tcp_server class encapsulation, the compiler would complain "handle_accept is not declared". I'm just wondering if the compiler automatically forward declare all the functions defined in the same class. Can anyone explain why?

like image 827
spiritsaway Avatar asked Jan 06 '15 10:01

spiritsaway


Video Answer


1 Answers

Functions defined in the definition of a class have exactly the same semantics as if they are only declared in the class definition and then defined immediately after the class definition. The only difference is that such member functions are implicitly declared inline while a function definition is either not-inline or explicitly inline. That is, from the compiler's point of view the functions are declared and the class is defined before the function definitions are considered.

The reason for defining the function after the class definition is simple: without doing so, the class would be incomplete and look-ups of members would fail which is clearly not desirable for member function definitions. As a side effect, functions can readily refer to each other. Since defining member functions in the class definition is primarily for convenience it would also be somewhat inconvenient to require declaration for member functions used later.

like image 55
Dietmar Kühl Avatar answered Oct 24 '22 17:10

Dietmar Kühl