Jump to content

  • Log In with Google      Sign In   
  • Create Account


Forward declaration, how and when do we use it?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
8 replies to this topic

#1 Meerul264   Members   -  Reputation: 130

Like
0Likes
Like

Posted 30 July 2013 - 08:21 AM

Now I know they're already a lot of threads talking about this. But no matter how much I read, I still can't seem to understand! So I decided to give it a try here - plus, I can ask a question myself here.

 

Suppose I have 2 classes; class A and class B. Both Have their own .cpp and .h files. I heard that if two classes need to use each other's member variables (quite often in game programming, I've come across a lot, but don't know how to.)

 

So how do I do forward declaration so that class A can access class B, and class B can access class A?

I might want to implement this on inventory - item class for my game.

 

Note that class A and class B are NOT declared and defined in the same .cpp file. Thanks :)

 



Sponsor:

#2 zacaj   Members   -  Reputation: 643

Like
0Likes
Like

Posted 30 July 2013 - 08:49 AM

A.h:

class B; //forward declaration

class A
{
//contents
}

B.h:

class A;

class B
{
//contents
}

A.cpp:

#include "A.h"
#include "B.h"

//code 

B.cpp:

#include "B.h"
#include "A.h"

//code

This is the safest way.  Basically you can't include a file that includes the first file.  

 

Forward declaring a class allows you to define pointers using that type, but not access them.  

 

So in class A you can have

 

B* b;

 

but you can't have an inline constructor that calls a function in b or accesses its variables.

 

Since you don't usually #include a .cpp file directly, it's safe to just include all the classes .h files in your .cpp files


Edited by zacaj, 30 July 2013 - 08:50 AM.


#3 Meerul264   Members   -  Reputation: 130

Like
0Likes
Like

Posted 30 July 2013 - 09:31 AM


Forward declaring a class allows you to define pointers using that type, but not access them.  

 

I'm don't follow this. Example please? thanks :)



#4 rip-off   Moderators   -  Reputation: 8164

Like
3Likes
Like

Posted 30 July 2013 - 09:38 AM

Usually, it is better to try and structure your game so there is a clear direction to such dependencies. For instance, I can see why an inventory needs to know about items, but why does the item care about inventories? What about items on the ground?

 

Such a cyclical dependency is harder to reason about, and harder to test in isolation.



#5 zacaj   Members   -  Reputation: 643

Like
0Likes
Like

Posted 30 July 2013 - 09:40 AM

class Foo;

Foo *foo_pointer; //valid.  It's just a pointer, so it only needs to know that Foo is a type (which it does from the forward declaration), it doesn't need to know anything about Foo itself

Foo foo;  //error.  Actually making a variable of type Foo (foo_pointer is of type Foo*, not Foo) can't be done, because we don't know how big Foo is.

void accessFoo(Foo *foo)
{
   foo->x=4;//also an error.  We don't know what variables Foo contains, so there's no way we could access them
}

class Foo
{ 
public:
    int x;
};
//declaring the type Foo down here doesn't affect the code above it

Foo foo2; //this is now valid, because Foo is a fully defined type

void main()
{
    foo_pointer=new Foo();//although foo_pointer was declared above the Foo class, since *this* code is below the Foo class, it can access foo_pointer's members
    foo_pointer->x=8;
    accessFoo(foo_pointer);
}



#6 Dave Hunt   Crossbones+   -  Reputation: 2434

Like
0Likes
Like

Posted 30 July 2013 - 10:32 AM

You might find Organizing Code Files in C and C++ a good read.



#7 Norman Barrows   Crossbones+   -  Reputation: 2058

Like
0Likes
Like

Posted 30 July 2013 - 11:49 AM

typically for an inventory system, you'll have a master database of inventory item types, and some sort of list data structure that can hold a list of instances of individual items.

 

i call mine a "stufflist". <g>      

 

its a list of stuff.  

 

stuff laying on the ground in a given area, stuff the player is carrying, stuff a NPC has for use in combat, stuff you find in a treasure chest, stuff available for trade, stuff installed on a vehicle, stuff carried in a cargo bay, etc.  

 

then different things in the game (PCs, npcs, stores, treasure chests, vehicles, etc) have their own stufflists.

 

all inventory actions are about adding items to, removing items from, or transferring items between, stufflists.

 

this usually does not require circular dependency between the parts of the system.

 

the item types database has the data such as base price, weight, is_weapon, weapon_type, is_missile_weapon, ammo_type, damage, rate of fire, time to manufacture, rendering info (how to draw it), etc. 

 

the stufflists have the ability to add and remove objects, and perform calculations such as total weight of items in the list, and can do searches for items based on type, quality, etc.

 

so at the low level you have the item types database, at the mid level you have the stufflist API for managing items, and at the high level you have the controlling code that manipulates the stuff lists to do things such as move all the items in the treasure chest to the player's inventory ("Take all").

 

note that each stufflist is in essence a little database of its own. fields in its records would be things like itemtype, quantity, quality, % completed (if under construction / being manufactured), position and rotation (for dropped items), etc.

 

things like encumbrance checks, container checks (do they have enough containers to carry it?), out of cargo space checks, out of hull space checks, etc would be done by the controlling code.


Norm Barrows

Rockland Software Productions

"Building PC games since 1988"

 

rocklandsoftware.net

 


#8 VReality   Members   -  Reputation: 436

Like
0Likes
Like

Posted 30 July 2013 - 01:36 PM

Meerul264,

You may have been misinformed about forward declarations.  One thing a forward declaration does not give is visibility on class members. 

 

Gaining Visibility on Class Definitions

 

This is generally done by including headers.  As zacaj shows above, A.cpp can include B.h to see and use B's public members, and B.cpp can include A.h to see and use A's public members. 

 

A.h:

class A
{/*members declared here*/};

B.h:

class B
{/*members declared here*/};

A.cpp:

#include "A.h" // Includes A's class definition (so members declared in it can be defined here).
#include "B.h" // Includes B's class definition (so members of A can see and use B and its public members).
...

B.cpp:

#include "B.h" // Includes B's class definition (so members declared in it can be defined here).
#include "A.h" // Includes A's class definition (so members of B can see and use A and its public members).
...

Header inclusion gets you visibility on a class definition.  Forward declarations are neither necessary nor sufficient.

 

When to Use Forward Declarations

 

Forward declarations are for cases in which the compiler needs to know that something is defined elsewhere, but doesn't need the details of that definition. 

 

A.h:

class B; // Forward declaration

class A
{B * pB;};  // Use of B, but not of B's definition

In this case, the compiler doesn't need to know anything about B here except that it's a class which is defined somewhere.

 

Note that we could include B.h here instead.  However, that would unnecessarily include B.h everywhere that A.h is included (which is bad for compile times). 

 

Also, there are cases when you can't include a header:

 

A.h:

#include "B.h" // Error - B.h includes this file

class A
{B * pB;}; 

B.h:

#include "A.h" // Error - A.h includes this file

class B
{A * pA};

Trying to include header files here results in infinite include recusion.

 

Include guards and "#pragma Once" can't solve this issue.  They will prevent the recursion, but will result in a reference to an undefined type.  If you can imagine the compiler reading A.h, it would include B.h, whithin which it would effectively ignore the directive to include A.h, then would parse the definition of B, which includes a reference to A, which would not yet be defined.

 

Forward declaration is the only way to make this work.

 

That being said, you'll run into other problems when you have classes mutually depending on each other in this way.  As mentioned above, in this case you should probably re-design to reduce dependancies.  I generally only use forward declarations to eliminate unnecessary include directives.

 

Forward Declarations Can Only Do So Much

 

Note that forward declarations allow A and B to contain pointers to each other because the compiler doesn't need to know the details of a class to define a pointer to that class.  This wouldn't work for member objects.

 

A.h:

#include "B.h" 

class A
{B MyB;}; 

In this case we must include the full definition of B.  The compiler needs its details in order to fully define A.  Because of this, there's no way for B to then contain a member of type A.  Forward declarations don't make recursive class definitions possible.


Edited by VReality, 01 August 2013 - 05:06 PM.


#9 JohnnyCode   Members   -  Reputation: 227

Like
0Likes
Like

Posted 30 July 2013 - 04:09 PM

Generaly, forward declaration is neccesary only if the declaration of class A needs to understand declarations of class B and vice versa, so it does not apply for definitions. To put siimply, suppose you have class CNode and class CScene. CScene needs to know about CNode, and suppose CNode definition needs to know about CScene as well, BUT, only on the definition manner. See this.

 

CNode.cpp:

#include "CScene.h" // vital and unavoidable!

CNode::Release()

{

 m_pScene->RemoveNode(this); // m_pScene is of CScene* type;

}

 

If you want to write such a definition of a CNode function, you need to include CScene.h header to CNode.cpp, ||||BUT THIS IS POSSIBLE ONLY IF CScene,h does not include Cnode.h!||||. But unluckily you find yourself in CScene declaration in following situation:

 

CScene.h:

#include "Cnode.h" // can be removed if following line is uncommented

// class CNode; // this is forward declaration, needed to type members of somewhere in declaration of CScene

class CScene

{

.......

CNode* GetNodeByName(char* name);

......

}

Do you see that forward declaration allowed leaving include of CNode.h from CScene.h , thus allowing to use CScene.h in CNode.cpp  definitions while having CScene members correctly typed if they use CNode on declaratoin level.






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS