tags:

views:

65

answers:

3

Hi

I'm a cpp newbie and i have a little question:

this is my header:

#ifndef TIMING_H
#define TIMING_H

#define MAX_MESSAGES 1000
typedef Message* MessageP; //inside the class?

class Timing {

public:

 Timing();

private:

 struct Message {
  Agent *_agent;
  double _val;
 };

 MessageP* _msgArr;
 int _waitingMsgs;


};

my question is do i have to place the typedef inside the class block right above MessageP* _msgArr or is it ok to place it near all the #define..
it doesn't output compilation errors so i'm not sure about it..

Thanks

+3  A: 

Outside of the class, that type must be referred as Timing::Message, so

typedef Timing::Message* MessageP;

But this is possible only after the declaration of Timing::Message, yet MessageP is used before the declaration of Timing is complete, so it's not possible.

Moreover, the struct is a private: member, so you can't define this outside anyway. The typedef must be done inside the Timing class.

class Timing {

public:

 Timing();

private:

 struct Message {
  Agent *_agent;
  double _val;
 };

 typedef Message* MessageP;   // <--


 MessageP* _msgArr;
 int _waitingMsgs;


};

You did not get compilation error probably because another Message type in global scope already exists.

KennyTM
One could use a forward declaration so that it doesn't have to be inside the class.
bobbymcr
@Bobby: Since it doesn't depend on `Timing`, it could be un-nested and defined before it. There is no way to forward-declare it in global scope without un-nesting.
Potatoswatter
Oh, I missed that part... so yes, I agree with you.
bobbymcr
+1  A: 

Put the typedef in a place where it makes sense.

Putting it at the top would mean that you inject the alias at global namespace scope. Putting it inside the class may mean that it is world viewable or viewable only to members (and/or subclasses thereof) depending on the nearest access specifier (or private if there aren't any).

If clients of the class doesn't need to know about this alias mark it as private.

If you put it inside the class: Do note however that outside of the class you will need to fully qualify the name as Timing::MessageP or else need a using Timing::MessageP directive in scope. Also, full qualification can be done only once the class has been defined (you cannot create aliases for incomplete types -- forward declaring Timing will thus not work).

class Timing {
    public:
     Timing() {}
    private:

 struct Message {
  Agent *_agent;
  double _val;
 };

 MessageP* _msgArr;
 int _waitingMsgs;

};

typedef Timing::Message* MessageP; // okay
dirkgently
A: 

It is OK to out it at the top. However, it is not a good practice to put it in global scope like the others mentioned.

snk