Is there a way to declare a class and then initialize it in a function in C ++?

I would like to know if there was a way to declare a class before a function and then initialize it inside the function, something like this:

Application.h:

class Application
{
  Application(HWND hwnd);
  ~Application() {}
};

main.cpp:

#include "Application.h"
#include <Windows.h>

Application App;

int main()
{
  App(hwnd);
  return 0;
}
+3
source share
3 answers
Application *pApp;

int main()
{
  pApp = new Application(hwnd);

  //use pApp

  delete pApp;
  return 0;
}

Using a pointer is pretty much the only way to do what you want to do.

+1
source

, . , , , . ++, , .

0

In C ++, the constructor for an object is called when storage is allocated for it; you cannot call the constructor later, as you tried to do.

You can not define a constructor and use a separate member function, for example init, to initialize your application object.

Application.h:

class Application
{
public:
    void init(HWND hwnd);
};

main.cpp:

#include "Application.h"
#include <Windows.h>

Application App;

int main()
{
    App.init(hwnd);
    return 0;
}
0
source

All Articles