Why does "class" at the top of a header file work?

Started by
11 comments, last by GameDev.net 15 years, 9 months ago
A pointer is merely a memory address. If you're running a 32 bit application the pointer size is 32 bits. Its merely the address of some chunk of memory. A 64-bit application has 64-bit pointer size.

A pointer bears no resemblance to what sort of object its pointing to. This is why there is a void* type in C/C++. This void* simply declares a pointer to anything.

class Foo{public:	int a;};class Bar : public Foo{public:	int b;};int main (){	printf ("%d, %d, %d\n", sizeof(void*) sizeof(Foo*), sizeof(Bar*));	return 0;}


Output (32-bit compiler):
4, 4, 4
Advertisement
Quote:Original post by thre3dee
A pointer bears no resemblance to what sort of object its pointing to. This is why there is a void* type in C/C++. This void* simply declares a pointer to anything.
A void* is an address to any primitive type or object, but a void* cannot (portably) hold an address of a function or class-member.
Quote:Original post by Evil Steve
class foo; is a forward declaration; it just tells the compiler that foo is a class, and you'll give it the definition of it later.

Because the compiler doesn't know the classes size or anything, you can only use pointers or references to the class, and not call any class methods until you include the header.

Usually you'd use the forward declaration in the header, so you don't pull foo's header into that file, and then you'd #include "foo.h" in bar.cpp, so you can call it's methods and so on.

Or if you're passing or returning by-value.

i.e.

class Foo;class Bar{public:    Foo BarMethod( Foo f );   };


Is also ok. :)
I wish it were the same for enums.

This topic is closed to new replies.

Advertisement