Jump to content

  • Log In with Google      Sign In   
  • Create Account


Why does this work?(Class prototype?)


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
3 replies to this topic

#1 Conny14156   Members   -  Reputation: 259

Like
1Likes
Like

Posted 22 March 2014 - 11:48 AM

Hi,

I was wondering if anyone could tell me if I should do it this way and why it works

 

I have two classes, class A and class B in two differently headers.

 

in class A header I have

#include "b.h"
class a
{
  b testVar;
}

and in class B Header I have 

#include "a.h"
class b
{
 a testVar;
}

if I do it this way, the compiler gonna complains about alot of stuffs >.<,

but instead of including I somehow(accidently) got

class a;
class b
{
  a testVar;
}

and I was wondering how this worked? is it like extern/global variables? or is it more of a function prototype, but how would class a inside b.h, knows that it got defined inside a.h? and how come those two doesnt clash in name if it doesnt work as a prototype? 



Sponsor:

#2 Melkon   Members   -  Reputation: 500

Like
6Likes
Like

Posted 22 March 2014 - 11:52 AM

This is "Forward declaration"

You say that there is a class "a", and the compiler shouldn't know anything about it, because in the header you don't use the functions and variables in "a".

 

http://en.wikipedia.org/wiki/Forward_declaration

 

And yes, it's good, you include less file, so you will compile faster. If you can forward declare something, it's a good idea to do it.


Edited by Melkon, 22 March 2014 - 11:53 AM.


#3 Endurion   Crossbones+   -  Reputation: 3473

Like
2Likes
Like

Posted 22 March 2014 - 12:52 PM

Note however forward declaration only works if the compiler doesn't need to know anything of the inner parts of that class. This means you can only forward declare pointers or references, not direct objects.


Edited by Endurion, 22 March 2014 - 12:52 PM.

Fruny: Ftagn! Ia! Ia! std::time_put_byname! Mglui naflftagn std::codecvt eY'ha-nthlei!,char,mbstate_t>

#4 Conny14156   Members   -  Reputation: 259

Like
0Likes
Like

Posted 22 March 2014 - 01:02 PM

Note however forward declaration only works if the compiler doesn't need to know anything of the inner parts of that class. This means you can only forward declare pointers or references, not direct objects.

That what I was actually using it for, in one of my classes I had a parameter class pointer, and now I know its a "legit" thing I think I have other places where I can do similar things instead of the way I have done it untill now!






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