Reputation: 531
The question is simple, I guess I cannot do this: (Im in the header file)
typedef struct {
myclass *p;
...
} mystruct;
class myclass {
private:
mystruct *s;
...
}
Because when the compiler reaches the struct it doesnt know what myclass is, but I cannot do the reverse either for the same reason:
class myclass {
private:
mystruct *s;
...
}
typedef struct {
myclass *p;
...
} mystruct;
How can I make that possible ? Im guessing there is some way to say the compiler "There is an struct called mystruct" before the class (2 example) so it knows that mystruct *s
it's possible but I cant manage to do it right. Thanks
Upvotes: 1
Views: 3476
Reputation: 42868
You need to use a forward declaration:
class myclass;
typedef struct {
myclass *p;
...
} mystruct;
class myclass {
private:
mystruct *s;
...
}
Now the compiler knows that myclass
is a class when it first sees it.
Also, no need to typedef structs in C++. You can simply write:
struct mystruct {
myclass *p;
...
};
Which does the same.
Upvotes: 10
Reputation: 315
First of all, typedefs shouldn't be used anymore in modern C++ (there is better syntax). For structs just use:
struct mystruct {
...
}
Also maybe consider a redesign so that you don't have 2 types dependent on each other. If it's not possible, then as others have said forward declare the types before.
Upvotes: 0
Reputation: 29352
In general, it is possible to declare a pointer to a class that has not been defined yet. You need only to have "declared" the class (class myclass).
This is the general solution to define classes with cross-references.
Upvotes: 1