0

I have two classes like this:

class B; class A { public: int a, b; B *b; public: int getctxt() { b->getctxt1(); } } Class B { public: int c,d; A *a; getctxt1() { /* something */ } } main() { B *b = new B(); A *a = new A(); b->a = a; a->b = b; } 

But when I try to compile, it says

invalid use of incomplete type ‘struct A’.

Can anyone tell me how to solve this?

3
  • 3
    Shouldn't there be a semicolon ; at the end of each class declaration? ;-) Commented Oct 13, 2013 at 20:59
  • See here: stackoverflow.com/questions/19343279/… Commented Oct 13, 2013 at 21:01
  • There is no invalid use of incomplete type ‘struct A’ in your code. There are lots of other errors, though. Please post code that is related to the problem description (or a problem description that matches the code). Commented Oct 13, 2013 at 21:04

3 Answers 3

2

Inline class member function definitions are parsed as if they appeared right after the class definition. Of course B isn't defined at that point. So move the member function definition for A::getctxt out of the definition of class A:

class B; class A { int getctxt(); /* ... */ }; class B { /* ... */ }; int A::getctxt() { b->getctxt1(); // at this point, *b has complete type! return -35; } 
Sign up to request clarification or add additional context in comments.

2 Comments

I did that. STill I get the same error :(.. I moved the definition of the getctxt() outside A.
@user1667630: Did you move it past the definition of B?
0

This is the reason why it is recommended to separate your classes in a .h file and a .cpp file. When you write class B;, you are telling the compiler that there is a class called B, but that's it, the compiler does not know what is inside this class. When the compiler reaches the line b->getctxt1();, it knows that b is an instance of B, but it does not know if getctxt1() is a method of B, because that is below. If you are writing all in a single file, you should first write all the declarations, and then all the implementations.

Comments

0

didn't anyone notice Class B syntax error? lowercase class is correct. and those two public members in A with the same name int b and B *b.

once you remove those and finish class definitions with semicolons, add a void type to the void getctxt1() that is missing it in B.

just define functions as they should be defined. not inline without a reason that you know which is!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.