Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ class use of undefined type

Tags:

c++

class

I have a class that I made that I am using in thread above the class. Even though I did a prototype of the class at the top it still throws off those errors error C2027: use of undefined type 'foo'

class foo;

DWORD WINAPI demo(LPVOID param)
{
    foo a;
}


class foo
{
public:
int x;
};
like image 849
Drake Avatar asked Jan 20 '23 19:01

Drake


1 Answers

Even though I did a prototype of the class

With a forward declaration of the class you can create pointers and references to the class. This is because pointers/references are represented the same across all classes/structs/etc. They're all just addresses of memory. So, for example, you could create a second class that can accept or contains pointers or references before fully defining the class, ie:

  class Bar
  {
  private:
      foo* aFoo;
  public:
      Bar(foo* foo2) : aFoo(foo2) {}
  };

However, until the compiler sees the full definition of the class, you can't instantiate it. Otherwise the compiler doesn't know how much memory to allocate and how to call the constructor and other methods. In most cases, C++ expects things to be defined before they are used. Forward declaration lets you get around this a little bit because pointers and references for any class are identical. So you can promise to the compiler you'll fully define it later.

like image 100
Doug T. Avatar answered Jan 30 '23 08:01

Doug T.