Archived

This topic is now archived and is closed to further replies.

Mrs Kensington

instance of derived class in super class

Recommended Posts

Inmy program i'm writing I want to have an instance of a class in its super class, but I can't seem to get it to work. for example...
class foo
{
	bar b;
};

class bar : public foo
{
};
 
comes up with the following compiler errors... error C2146: syntax error : missing ';' before identifier 'b' error C2501: 'foo::b' : missing storage-class or type specifiers error C2501: 'foo::bar' : missing storage-class or type specifiers This is obviously because when the instance of bar is created it doesn't know about class bar. Is there any way of declaring the class earlier like you can do with methods??? Thanks alot Ford! theres an infinate amount of monkeys outside wanting to talk to you about a script of Hamlet they created!
www.mikeditum.co.uk
[edited by - mrs kensington on October 14, 2003 7:38:26 PM]

Share this post


Link to post
Share on other sites
you can''t. each instance of bar contains a foo (it is derived from it), so each instance of bar would have an internal instance of bar, which itself has an internal bar, etc etc...

you could store a pointer to it, though...

and yes, you can foward declare classes, just put "class bar;" before it is used.

Share this post


Link to post
Share on other sites
AFAIK, if you forward declare a class... you can only use references, and pointers to it. This means you could say:
class bar;

to declare bar as a class... ie:

class bar;

class foo
{
public:
foo( bar& B ) : b(B) {}
bar& b;
};

class bar : public foo
{
public:
bar() : foo( *this ) {}
};

I made the constructor in foo, to initialize the reference on creation. This meant that bar needed a constructor, to tell it how to initialize the foo element of bar. Obviously, you can set it up how you need. Hope this helps .

EDIT: If you need to change the bar that foo points too, obviously, use a pointer, instead of a reference.

[edited by - dmounty on October 14, 2003 8:07:07 PM]

Share this post


Link to post
Share on other sites