Reputation: 2646
I would like to know if there was a way to declare a class before a function, and then initialize it inside of a 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;
}
Upvotes: 3
Views: 107
Reputation: 11582
In C++ the constructor for an object is called when the storage for it is allocated, you cannot call the constructor later like you tried to do.
You might consider not defining a constructor, and using a separate member function, for example init
, to initialize your App 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;
}
Upvotes: 0
Reputation: 6039
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.
Upvotes: 1
Reputation: 26164
You cannot initialize a global object inside a function, the constructor of the object will be called some time before the main function of the program is called. This is very bad, it involves the thing called static initialization fiasco and you want to avoid it. Try to search for singleton pattern implementation in C++, that's what you need probably.
Upvotes: 0