Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand the typedef in this declaration

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;

like image 380
Lixun Bai Avatar asked Mar 12 '17 08:03

Lixun Bai


2 Answers

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 
like image 92
songyuanyao Avatar answered Sep 22 '22 03:09

songyuanyao


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&);
like image 29
Rakete1111 Avatar answered Sep 20 '22 03:09

Rakete1111