Empty class declarations

J

jonathanho15

Sometimes, when I browse through some code, I see declarations like:

class SomeClass;

These make absolutely no sense to me. Can anyone tell me what these
kind of declarations do?

Thanks!
 
J

jonas.email

This is forward declaration. When using a class "ClassA" as a member in
another class "ClassB", you will define "ClassB" before "ClassA". But
if "ClassB" also have a member of "ClassA" you have a cycle. You can
solve this problem by using forward declaration.

class ClassA; // forward declaration

class ClassB {
public:
ClassA a;
};

class ClassA {
public:
ClassB b;
};
 
M

Mike Wahler

This is forward declaration. When using a class "ClassA" as a member in
another class "ClassB", you will define "ClassB" before "ClassA". But
if "ClassB" also have a member of "ClassA" you have a cycle. You can
solve this problem by using forward declaration.

No, a forward declaration does not solve the situation you
show below, which simply cannot be resolved. (Think about it
for a moment). A forward declaration only allows a pointer
or reference to the forward-declared class to be declared without
its full class definition visible.
class ClassA; // forward declaration

class ClassB {
public:
ClassA a;
/* ERROR */
};

class ClassA {
public:
ClassB b;
};

class ClassA;

class ClassB
{
ClassA a; /* ERROR */
ClassA& r; /* OK */
ClassA *p; /* OK */
};

class ClassA
{
};

class ClassC
{
ClassA a; /* OK, full def of ClassA visible */
};

-Mike
 
R

Rolf Magnus

Mike said:
/* ERROR */

And just as a side note: If that worked, it wouldn't make much sense to do
it anyway, since an instance of ClassA - as well as an instance of ClassB -
would need infinite storage.
 
M

Mike Wahler

Rolf Magnus said:
And just as a side note: If that worked, it wouldn't make much sense to do
it anyway, since an instance of ClassA - as well as an instance of
ClassB -
would need infinite storage.

That's what I'd hoped to make 'jonas' realize, with
my "think about it for a moment" remark.

-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,203
Messages
2,571,059
Members
47,668
Latest member
SamiraShac

Latest Threads

Top