How to forward declare a function within the same class?

Viewed 110

There is a class A having all the declarations and definitions are placed inside as shown below:

class A
{
  void f(); // forward declaration for a lengthy method
  ...
  void g()
  {
    f();    // call the above forward-declared method
  }
  void f()  // definition of a lengthy method
  {
    ...
  }
}

I don't want to take f() out of the class header like A::f(), but just want to keep all the source within the class. However, when I compile it, I get the following error:

error C2535: 'void A::f()': member function already defined or declared
note: see declaration of 'A::f'

Isn't there any way to resolve this issue?

1 Answers

You don't need to forward declare the member function. And you cannot both forward declare, and define a member function within the class definition - If you forward declare, then you must define the member function outside of the class definition.

Member function definitions are in a "complete class context", which means that they have access to all members of the class, even those declared after the function body.

As such, your example can be fixed by removing the first declaration of f.

Related