1

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

1
  • 5
    Please, no more typedef struct { ...} xyz; In clean C++ you write struct xyz { ...}; and the type is defined... Commented May 24, 2015 at 13:47

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

3 Comments

Sorry for that, Im comming from C and new to C++. Is typedef struct { ... } mystruct; just the same as struct mystruct { ... } ? Do they have any difference ?
@Ediolot They are exactly the same. In C++, you can simply write struct mystruct {…}; and refer to the struct by its name: mystruct, no need to prepend struct before the name as in C. And consequently, no need to typedef it.
It's not the same, but they are similar. You will struggle to forward declare a typedef struct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.