0

I wrote a simple smart point class but get in to trouble. The code BPtr mBptr; in class A gose well while compiling, but failed in some other class with error: "error C2027: use of undefined type". So i have to include the B.h in header file rather then use forward declaration. I have no idea what`s going on. Dose anyone know about it? I wrote these code like this:

//Pointer.h
template<class T>
class Pointer
{
public:
    Pointer(T* pObject = nullptr);
    ...
private:
    T* mPtr;
};
//Pointer.inl
template <class T>
Pointer<T>::Pointer(T* pObject)
{
    mPtr = pObject;
    if (mPtr)
    {
        mPtr->IncreRef();//IncreRef: function of class T
    }
}
...

And i used in this way:

//A.h
#include "Pointer.h"

class B;
typedef Pointer<B> BPtr;

class A
{
public:
    A();
    ~A();
private:
    BPtr mBptr; //This might compiler error c2027
};
//A.cpp
#include "A.h"
#include "B.h"
A::A()
{
}

A::~A()
{
}
  • 1
    Where do you `#include "Pointer.inl"`? (FYI: [SO: Why can templates only be implemented in the header file?](https://stackoverflow.com/q/495021/7478597)) – Scheff's Cat Dec 20 '21 at 08:21
  • 3
    *"but failed in some other class with error: "error C2027: use of undefined type". "* - A proper [mcve] that produces that specific condition *for us* is what your post should include. – WhozCraig Dec 20 '21 at 08:23

1 Answers1

0

BPtr mBptr creates an object.

As the constructor of Pointer calls a method of B, B needs to be fully defined at the point that mBptr is declared.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • I know i have to include B.h in header file, but it has no errors in my example code when i use forward declaration "class B", how can it be. – PurpleBH Dec 20 '21 at 09:09