Classses of each other

J

Jon Slaughter

I'm trying do to the following

class Edge
{
Node *N;

....
}


class Node
{
Edge *E;

...
}


But ofcourse I get an error that I assume is because of scope. Is there any
way to get something like this to work?

Thanks,
Jon
 
S

Sep

Forward declare class Node so that the parser knows about it when
declaring N.

class Node;

class Edge
{
....
 
J

Jon Slaughter

Sep said:
Forward declare class Node so that the parser knows about it when
declaring N.

class Node;

class Edge
{
...

I tried that... But it didn't work(I added a public member a into Node and
tried to access it in edge but I get an error... I will try again and see,
maybe I mised something.
 
S

Sep

Well, if that's your exact code, then you're missing the semicolons
after the ending curly brackets for the classes which are not optional,
that would give you a syntax error.
 
J

Jon Slaughter

Sep said:
Forward declare class Node so that the parser knows about it when
declaring N.

class Node;

class Edge
{
...

ok, I tried that, but when I try to access members of Node in Edge, I get an
error ;/

Heres the exact code

class Node;

class Edge

{

Node *N;

public:

Edge() { };

~Edge() { };

void func(int d)

{

N->a = d;

}

};



class Node

{

Edge *E;

public:

int a;

Node() { };

~Node() { };

};

void main(void) { Node T; }





The errors I get are

use of undefined type Node and left of ->a must point to a
class/struct/union.
 
S

Sep

That error is because you are trying to use an object of a type that
has not yet been fully defined.

If you are trying to use an object of a type, the type must be fully
known at the time of use. To fix this, seperate the definition of
function func from its declaration and place it after Node has been
defined.

class Node;

class Edge
{
....
void func(int d);
};

class Node
{
....
};

void Edge::func(int d)
{
N->a = d;
}
 
J

Jon Slaughter

Sep said:
That error is because you are trying to use an object of a type that
has not yet been fully defined.

If you are trying to use an object of a type, the type must be fully
known at the time of use. To fix this, seperate the definition of
function func from its declaration and place it after Node has been
defined.

class Node;

class Edge
{
...
void func(int d);
};

class Node
{
...
};

void Edge::func(int d)
{
N->a = d;
}


Ok, I should have known that ;) Thanks! I guess I was expecting the compiler
to look a head when I referenced Node but I should have known better since I
had problems with that already.

Thanks again.

Jon
 

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

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,044
Latest member
RonaldNen

Latest Threads

Top