Microsoft KB Archive/136005

= How to declare classes that refer to the each other in Visual C++ =

Article ID: 136005

Article Last Modified on 9/1/2005

-

APPLIES TO


 * Microsoft Visual C++ 1.0 Professional Edition
 * Microsoft Visual C++ 1.5 Professional Edition
 * Microsoft Visual C++ 1.51
 * Microsoft Visual C++ 1.52 Professional Edition
 * Microsoft Visual C++ 1.0 Professional Edition
 * Microsoft Visual C++ 2.0 Professional Edition
 * Microsoft Visual C++ 2.1
 * Microsoft Visual C++ 2.2
 * Microsoft Visual C++ 4.0 Standard Edition
 * Microsoft Visual C++ 4.1 Subscription
 * Microsoft Visual C++ 5.0 Enterprise Edition
 * Microsoft Visual C++ 6.0 Enterprise Edition
 * Microsoft Visual C++ 5.0 Professional Edition
 * Microsoft Visual C++ 6.0 Professional Edition
 * Microsoft Visual C++ 6.0 Standard Edition

-



This article was previously published under Q136005



SUMMARY
In C++, you may need to have two classes that contain data members that refer to the other class as in this example: class B { A * x; };

class A { B * x; }; This article shows by example how to declare two classes that contain pointers to the other class. The two classes (A and B) are derived from other classes (C and D) to better demonstrate this issue.

If the two classes are not declared correctly, errors such as the following can occur:

test1.h(8) : error C2501: 'B' : missing decl-specifiers

test1.h(8) : error C2143: syntax error : missing ';' before '*'

test1.h(8) : error C2501: 'x' : missing decl-specifiers

Note In Visual C++ 6.0, the error message is similar to the following:

test1.h(8) : error C2143: syntax error : missing ';' before '*'

test1.h(8) : error C2501: 'B' : missing storage-class or type specifiers

test1.h(8) : error C2501: 'x' : missing storage-class or type specifiers

Sample code
/* Compile options needed: none

//================================ // test1.h //================================


 * 1) ifndef _a_
 * 2) define _a_

class B;

class A : public D { B * x; };


 * 1) endif

//================================ // test2.h //================================


 * 1) ifndef _b_
 * 2) define _b_

class A;

class B : public C { A * y; };


 * 1) endif

//================================= // test.cpp //=================================

class C { int q; };

class D { int p; };


 * 1) include "test1.h"
 * 2) include "test2.h"

void main(void) { }

Additional query words: 8.00 8.00c 9.00 9.10

Keywords: kberrmsg kbhowto kbinfo kbcode KB136005

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.