Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can member functions be called before being declared?

Tags:

c++

I have always been under the impression that C/C++ is parsed in 1 pass, therefore, a symbol must be declared before it can be used.

Thus this does not work:

void a()
{
   b();
}

void b() 
{
}

unless we forward declare void a();

However, I noticed that this does work:

class Foo 
{
  public:
  void a() 
  {
    b();
  }

  void b()
  {
  }
};

Why does this work? If C++ is parsed in a single pass through the code then this should not work I would think because the symbol Foo::b() has not been defined when it is called.

like image 313
jmasterx Avatar asked Mar 27 '26 06:03

jmasterx


1 Answers

The definition of your class:

class Foo 
{
public:
  void a()  {  b(); }
  void b()  {  }
};

has the same meaning than:

class Foo 
{
public:
  void a();
  void b();
};
void Foo::a()  {  b(); }
void Foo::b()  {  }

This is why the function body sees all the members, as if the class was already completely defined. This is by the ways stated in the C++ standard:

3.3.7/1 The potential scope of a name declared in a class consists not only of the declarative region following the name’s point of declaration, but also of all function bodies, brace-or-equal-initializers of non-static data members, and default arguments in that class (including such things in nested classes).

The compiler still parses the file in a single pass. But the parsing the grammatical construct is only a part of the larger compilation process, in which applying the context to the parsed grammar production plays also a role (see also this SO question).

like image 73
Christophe Avatar answered Mar 28 '26 19:03

Christophe



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!