Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Forward Declare a Property in C++/CLI?

I have a class in C++/CLI that I'd like to give a property. I want to declare the property in a header file and then implement that property in a .cpp file.

Here's the header:

public ref class Dude
{
    static property Dude^ instance
    {
        Dude^ get();    
    }
}

If I declare the header file and don't put anything in the cpp, i get the following error:

1>Dude.obj : error LNK2020: unresolved token (06000001) Test.Dude::get_instance

From this I concluded that I should implement the property as

  static Lock myInstanceLock;

   Dude^ Dude::get_instance()
   {

       if(myInstance == nullptr)
       {
           myInstanceLock.lock();
           if(myInstance == nullptr)
           {
               myInstance = gcnew Dude();
           }
           myInstanceLock.unlock();             
       }
       return myInstance;
   }

However, when I compile this code, I get a bunch of errors. The first error (The others are a result of the first one) is:

1>.\Dude.cpp(13) : error C2039: 'get_instance' : is not a member of 'Test::Dude'

Can anyone shed some light on this issue?

like image 262
Mark P Neyer Avatar asked Aug 24 '09 15:08

Mark P Neyer


People also ask

Can you forward declare a function?

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.

What is C++ forward declaration?

Forward Declaration refers to the beforehand declaration of the syntax or signature of an identifier, variable, function, class, etc. prior to its usage (done later in the program). Example: // Forward Declaration of the sum() void sum(int, int); // Usage of the sum void sum(int a, int b) { // Body }

Can you forward declare a struct C++?

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).

Why Forward declare instead of include?

A forward declaration is much faster to parse than a whole header file that itself may include even more header files. Also, if you change something in the header file for class B, everything including that header will have to be recompiled.


1 Answers

Change the implementation to:

Dude^ Dude::instance::get()
like image 173
mmx Avatar answered Sep 18 '22 20:09

mmx