Forward declaration and usage rules

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



I have compiled C++ code using g++ version 2.95.3 that seems to allow forward 
usage of *value*-types in a class declaration, against my expectations.  I only 
expected to be allowed forward usage of pointer-types and reference-types.  Note 
that this only applies to forward uses in the *declaration* - I have to include 
full headers before I can compile *definitions" of the member functions.

Does C++ allow arbitrary use of forward-declared types in class declarations?  
If not, does g++ relax these rules on forward declarations?  Would my code 
therefore not port to other C++ compilers?  Has the C++ standard changed 
recently to allow forward use of value-types inside class declarations?  Or is 
this actually a bug in g++? 

My actual example is a library of Real, Imaginary and Complex numbers (all 
value-types), for which mutually-recursive definitions would be very useful, if 
this style is eventually kosher and portable.  A cut-down model of the 
phenomenon is given below, which I have also tested:

--Tony Simons


// in file A.h =========================

 class B;  	// forward declaration
 
 class A {
 public:
 	A::A(float x);
 	B foo(int x) const;	// Unexpectedly OK!  Returns a B value
  	B bar(B b) const;	// Unexpectedly OK!  Accepts a B value too
 private:
 	float f;
 };
 
 #include "B.h"			// the full include is required here...
 
 inline A::A(float x) : f(x) {}
 
 inline B A::foo(int x) const {
 	return B(x);		// ...for this to compile, and also...
 }
 
 inline B A::bar(B b) const {
 	return B(b);		// ...for this to compile, as expected.
 }

 
// in file B.h ==========================
 
 class A;  // forward
 
 class B {
 public:
 	B::B(int y);
 	A bar(float y) const;	// Unexpectedly OK!  returns an A value
 private:
 	int i;
 };
 
 #include "A.h"			// the full include is required here...
 
 inline B::B(int y) : i(y) {}
 
 inline A B::bar(float y) const {
 	return A(y);		// ...for this to compile, as expected.
 }
 
 
 // in file main.cc =========================
 
 #include "A.h"
 #include "B.h"
 
 void main() {
 	A a (3.4);
 	B b = a.foo(2);
 	B c = a.bar(b);
 }




[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux