Recently, I read the book Effective C++ and there is a declaration about typedef in Item 35 which confuses me.
class GameCharacter; // Question1: Why use forward declaration?
int defaultHealthCalc(const GameCharacter& gc);
class GameCharacter{
public:
typedef int (*HealthCalcFunc)(const GameCharacter&); // Question 2: What does this mean?
explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc)
: healthFunc(hcf)
{}
int healthValue() const
{return healthFunc(*this); }
private:
HealthCalcFunc healthFunc;
};
So my first question is: Why does the author use a forward declaration here? Is there any specific reason?
And my second question is: How do I understand the typedef declaration, and how do I use it? I just know something like typedef int MyInt;
So my first question is that why the author use forward declaration here?
Because the declaration of the function defaultHealthCalc
uses const GameCharacter&
as the type of the parameter, then GameCharacter
needs to be declared in advance.
And my second question is how to understand the typedef declaration
It declares a type name HealthCalcFunc
, which is a type of pointer to function, which takes const GameCharacter&
as parameter and returns int
.
and how to use it?
Just as the code sample showed,
explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc) // declare a parameter with type HealthCalcFunc;
// the default argument is function pointer to defaultHealthCalc
: healthFunc(hcf) // initialize healthFunc with hcf
{}
int healthValue() const
{return healthFunc(*this); } // invoke the function pointed by healthFunc
HealthCalcFunc healthFunc; // declare a member with type HealthCalcFunc
The forward declaration is needed because of the forward declaration of defaultHealthCalc
, which uses GameCharacter
. Without forward declaration, the compiler would not know that later, there will be a type named GameCharacter
, and so you need to forward declare it, or move the definition before the function declaration.
That typedef
means to name the type int(*)(const GameCharacter&)
HealthCalcFunc
. That's a function pointer to a int(const GameCharacter&)
. For that reason, typedefs are pretty unreadable, it is advised to use a using
declaration instead:
using HealthCalcFunc = int(*)(const GameCharacter&);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With