2

Google c++ style has the following. I don't understand why forward declaration will call f(void*).

It can be difficult to determine whether a forward declaration or a full #include is needed. Replacing an #include with a forward declaration can silently change the meaning of code:

 // b.h: struct B {}; struct D : B {}; // good_user.cc: #include "b.h" void f(B*); void f(void*); void test(D* x) { f(x); } // calls f(B*) 

If the #include was replaced with forward decls for B and D, test() would call f(void*).

1
  • 1
    If you just do struct D; then the inheritance is not known. Commented May 15, 2018 at 15:19

1 Answer 1

5

Consider the two cases individually. By replacing the #include with the header's content, we first have :

struct B {}; struct D : B {}; void f(B*) {} void f(void*) {} void test(D* x) { f(x); } 

There are two possible overloads. Since D inherits from B then D* is implicitly convertible to B*. Out of B* and void* the first is a better match so that overload is chosen. But in the case of a forward declared B and D :

struct B; struct D; void f(B*) {} void f(void*) {} void test(D* x) { f(x); } 

D is not known to inherit from B so there is no implicit conversion possible from D* to B*. The only matching overload is f(void*).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.