use class inside another class

Jun 11, 2013 at 7:36pm
Hi,
I am having this problem : I want to include an object within another class, like this :

1
2
3
4
5
6
7
8
9
<apple.h>
class apple{
...
};

<pear.h>
class pear{
 apple appleobject; // <-- including another class.
}


any help on how to do this? since I can't include apple.h in pear.h and stuff like that...
thanks
Jun 11, 2013 at 7:53pm
From the code you have posted I don't see why you can't include apple.h in pear.h.
Jun 11, 2013 at 8:27pm
i spotted a little problem, you're enclosing the headers you made with angel brackets.
you use angle brackets to specify standard library headers.
your own made headers should be placed in double quotations, maybe this is your problem.

try using:
#include "apple.h"
and
#include "pear.h"
Jun 11, 2013 at 9:26pm
don't forget some include guards when writing your headers.
Jun 12, 2013 at 2:56am
hi, I think i should have clarified my question a bit more.
example of the kind of problem I'm having:
--- this is from main.cpp ---
1
2
#include "pear.h"
... 

--- this is from sub.cpp ---
1
2
#include "pear.h"
...

--- this is from pear.h ---
1
2
3
4
5
#include "apple.h"
class pear
{
   apple apple_object_in_pear;
};

--- this is from apple.h ---
 
class apple { ... };


the problem is when I include pear.h in both sub.cpp and main.cpp - everything in apple.h gets redefined and i get an error.
For variables I could work around this by using extern but I don't know how i can do it for classes
Jun 12, 2013 at 3:26am
actually, never mind, include header guards worked\
Jun 12, 2013 at 11:03am
zsteve wrote:
hi, I think i should have clarified my question a bit more.


you're correct, didn't really clarify your question, i thought you actually implemented include guards in your program before posting this.

anyway, i'm glad your project works.
Topic archived. No new replies allowed.