Reputation: 171
I'm allocating dynamic memory in my class as a private: variable
Then in the constructor I'm trying to initialize the array.
public
Display(int Width, int Height) {
nScreenHeight = Height;
nScreenWidth = Width;
DWORD dwBytesWritten = 0;
for (int i = 0; i < (nScreenWidth*nScreenHeight); i++) screen[i] = L'';
SetConsoleActiveScreenBuffer(hConsole);
}
private:
int nScreenWidth;
int nScreenHeight;
wchar_t *screen = new wchar_t[nScreenWidth*nScreenHeight];
If I try run the program an Exception Unhanded in thrown.
Unhandled exception thrown: write access violation. this->screen was 0x2096112.
While trying to initialize the buffer screen with L' '
Upvotes: 0
Views: 154
Reputation: 122486
Memebers are initialized in the order they appear in the class declaration before the body of the constructor is executed. So what happens is:
nScreenWidth
is default initialized (see here)nScreenHeight
is default initializedscreen
is initialized with new wchar_t[nScreenWidth*nScreenHeight]
nScreenWidth
and nScreenHeight
Use the initializer list for all members to avoid confusion:
Display(int Width, int Height) :
nScreenWidth(Width), nScreenHeight(Height), screen(new wchar_t[nScreenWidth*nScreenHeight])
{
DWORD dwBytesWritten = 0;
for (int i = 0; i < (nScreenWidth*nScreenHeight); i++) screen[i] = L'';
SetConsoleActiveScreenBuffer(hConsole);
}
Even better would be to use a std::vector<wchar_t>
, the constructor would be
Display(int Width, int Height) :
nScreenWidth(Width), nScreenHeight(Height), screen(Width*Height)
{
...
and instead of bothering about the rule of three/five you can rely on the rule of zero.
Upvotes: 3