0

Okay, so I'm running into trouble with Forward Declarations in Visual Studios C++ (C++/CLI). The code is as follows:

A.h

#include "B.h"

#ifdef B_H
#pragma once

public ref class A : public base_class  //base_class is public, memory managed 
{
    B^ b;
}

#endif

B.h

#define B_H

#pragma once

ref class A;

ref class B 
{
    A^ a;
}

#include "A.h"

The #ifdef/#pragma guards should keep be keeping a *.h from being read twice, and forcing b.h to be read first, and from the compiler output I'm pretty sure they are. (I'm not even sure the #ifdef/#define is needed with the #pragma once and #include placement)

But, the complier complains of a path/a.h: error C2011: 'class' type redefinition. See file path/B.h

Should I be doing something with the forward declaration of A because it's a derivative class in the actual class definition, or am I barking up the wrong tree?

Cas Gray
  • 3
  • 1
  • 2

1 Answers1

3

Two changes needed:

  1. Add semicolons after the closing brace of the class definitions.
  2. In A.h, move the #pragma once to be the very first line in the file. It's getting screwed up by having this inside the #ifdef block.

Also, note that a simpler way to do this would be to not have either header file include the other, and use forward declarations in both files:

A.h:

#pragma once
ref class B;
public ref class A : public base_class  //base_class is public, memory managed 
{
    B^ b;
};

B.h

#pragma once
ref class A;
ref class B 
{
    A^ a;
};
David Yaw
  • 27,383
  • 4
  • 60
  • 93
  • By shifting the #pragma once outside the #ifdef A is not defined if A.h is preprocessed first. Also, I need to use the methods of the references in the .cpp files so I need #include somewhere in the .h files, but using the second method and adding the #include at the bottom of the .h's works! Thanks! – Cas Gray Jun 01 '12 at 19:07
  • To solve that, I'd recommend that you remove that #include from the bottom of the header file, and simply #include both A.h and B.h from your .cpp file. – David Yaw Jun 01 '12 at 19:31
  • Isn't putting #include in .cpp files bad practice? (not that everything's not all mashed together after preprocessing anyway) – Cas Gray Jun 01 '12 at 19:45
  • Not that I know of. If your project is using preprocessed headers, it's usual to put #includes from outside your project into `stdafx.h` (such as `#include`), but for header files inside the project, it's normal to have a half-dozen #includes at the top of every .cpp file, or more. – David Yaw Jun 01 '12 at 20:49