HaeRim Lee
HaeRim Lee

Reputation: 53

How to forward declare a function within the same class?

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?

Upvotes: 2

Views: 525

Answers (3)

zerocukor287
zerocukor287

Reputation: 1050

If you really want to keep the declaration in the same header file here is one approach:

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

void A::f()  // definition of a lengthy method
{
  ...
}

That out-of-line definition of your lengthy method can be moved down in the header file, or if you decide move it to a source file.

Upvotes: 0

The Assem
The Assem

Reputation: 1

I guess while compiling the class ... a function declaration would be considered as a whole a function that doesn't need a definition at the moment at least till we finish the whole compilation process of a single class then the function get in the column of declared function that need to be declared, so when you declare and define in the same (class or struct) you would get a function overloading error, Plus it makes nonsense to forward declare and define in the same file.

Upvotes: 0

eerorika
eerorika

Reputation: 238351

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.

Upvotes: 6

Related Questions