Quick question...
Hello,
Can we create a class with some of its members residing on the stack and
some residing on the heap. Further, can we create an object of this class on
the heap and one on the stack?
Please consider the following code:
================================================
class Cat
{
public:
Cat(); //Default constructor
Cat(int Boxes); //Constructor
~Cat(); //Destructor
int getAge();
void setAge(int age);
private:
int *itsAge; //Created on the free store
int SandBoxes; //Created on the stack
};
//Constructor
Cat::Cat()
{
itsAge = new int(2);
}
//Constructor for object on stack
Cat::Cat(int Boxes)
{
SandBoxes = Boxes;
}
//Destructor
Cat::~Cat()
{
delete itsAge;
}
int Cat::getAge()
{
return *itsAge;
}
void Cat::setAge(int age)
{
*itsAge = age;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
WPARAM wParam, LPARAM lParam)
{
Cat *pCat = new Cat;
Cat xxx(22);
WM_PAINT:
pCat->setAge(99);
GetLastAge = pCat->getAge();
TextOut(hdc,100,300,
M_szBuffer,wsprintf(M_szBuffer,TEXT("%d"),GetLastAge));
return 0;
....Some other code....
====================================================
This code unfortunately doesn't even give an error at compile or build time.
However when I go to start it, it breaks and displays a "Microsoft
Development environment" window and says a vague message:
"Unhandled exception at 0X00412e28 in APP_.exe: OC0000005: Access violation
reading location 0Xccccccc0."
When I click on "Break" button of this window, it closes ansd a yellow arrow
pointing to the following line:
/* verify block type */
_ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));
in dbgdel.cpp file, which is not one of mine!
The program can work if I remove the following line though:
Cat xxx(22);
Can someone help me understand this problem, All sugestions are much
apreciated!
--
Best regards
Robert