Hi,
I have the following code.
class CVehicle
{
}
class CCar : public CVehicle
{
}
int main()
{
CVehicle *m_VehicleType;
CCar m_Car;
m_VehicleType = &m_Car;
delete(m_VehicleType); // Can i do this way
}
Printable View
Hi,
I have the following code.
class CVehicle
{
}
class CCar : public CVehicle
{
}
int main()
{
CVehicle *m_VehicleType;
CCar m_Car;
m_VehicleType = &m_Car;
delete(m_VehicleType); // Can i do this way
}
AFAIK attempting to call delete on an object allocated on the stack is undefined behavior. There's no guarantee what will happen - but it won't be anything good. Don't do it.
No. You have to pair new with delete, and new[ ] with delete[]. If there was no new, you must not call any delete for an object.Quote:
delete(m_VehicleType); // Can i do this way
Yes, even i am also thinking the same, becoz i have read many times that we need to use delete only on objects created by using 'new' operator. This is clear to me now.
So it means we should always use in this way
Base *ptr = new Derived();
if we want base class pointer to point to Derived object, am i correct ?
No, not necessarily. It all depends on how the classes are declared and what their lifetimes are.
In your example just remove the 'delete' line. The car object will be automatically destructed when the execution leaves 'main()'
Code:int main()
{
CVehicle *m_VehicleType;
CCar m_Car;
m_VehicleType = &m_Car;
} << m_Car destroyed here.
Hi, If we do this way, i mean removing the delete statement, is it not going to be a memory leak problem ?
No.
The CCar object is created within the body of 'main' and destroyed when it goes out of scope, automatically.