I have made two identical classes X and Y, with a pointer to each other. See the code below for X.h, Y.h is identical with all X's and Y's interchanged. This code gives however an error in my method Connect (error C2027: use of undefined type 'Y'). In X.h, I have forward declared the class Y, but it doesn't know that Y has a method named SetXPointer. Therefore I also need to forward declare this method, correct?
If I try to do this (adding the line Y::SetXPointer(X* pX_in); under the line class Y;), I get a compiler error C2761: 'void Y::SetXPointer(X *)' : member function redeclaration not allowed. Is there a way to use a public method of class Y in class X?
// X.h
#pragma once
#include "Y.h"
// Forward declaration
class Y;
class X
{
public:
X(void) : data(24) {};
~X(void) {};
int GetData() { return data; }
void SetYPointer(Y* pY_in) { pY = pY_in; }
Y* GetYPointer() { return pY; }
void Connect(Y* Y_in) { pY = Y_in; Y_in->SetXPointer(this); }
private:
int data;
Y *pY;
};
To write a forward declaration for a function, we use a function declaration statement (also called a function prototype). The function declaration consists of the function header (the function's return type, name, and parameter types), terminated with a semicolon. The function body is not included in the declaration.
In C++, Forward declarations are usually used for Classes. In this, the class is pre-defined before its use so that it can be called and used by other classes that are defined before this. Example: // Forward Declaration class A class A; // Definition of class A class A{ // Body };
In C++, classes and structs can be forward-declared like this: class MyClass; struct MyStruct; In C++, classes can be forward-declared if you only need to use the pointer-to-that-class type (since all object pointers are the same size, and this is what the compiler cares about).
In C++ the forward declaration lets the code following the declaration know that there is are classes with the name Person. This satisfies the compiler when it sees these names used. Later the linker will find the definition of the classes.
Don't include the method body in the class body. Write both classes, and after both classes are complete, write the method implementations:
class Y;
class X {
…
void Connect(Y* Y_in);
…
};
class Y {
…
void Connect(X* X_in);
…
};
inline void X::Connect(Y* Y_in) {
pY = Y_in;
Y_in->SetXPointer(this);
}
inline void Y::Connect(X* X_in) {
pX = X_in;
X_in->SetXPointer(this);
}
That way, full information about how the objects of the class will be layed out in memory is available by the time the Connect
method is implemented. And as a method in the class body and a method declared inline
will both be inlined the same way, performance will be the same as well.
The only downside is that you won't be able to split these two classes over two headers in a reasonable way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With