-
September 25th, 2008, 11:52 PM
#1
Clarify me on this example
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
}
-
September 26th, 2008, 12:10 AM
#2
Re: Clarify me on this example
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.
-
September 26th, 2008, 01:38 AM
#3
Re: Clarify me on this example
delete(m_VehicleType); // Can i do this way
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.
-
September 26th, 2008, 02:25 AM
#4
Re: Clarify me on this example
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 ?
-
September 26th, 2008, 04:13 AM
#5
Re: Clarify me on this example
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.
"It doesn't matter how beautiful your theory is, it doesn't matter how smart you are. If it doesn't agree with experiment, it's wrong."
Richard P. Feynman
-
September 26th, 2008, 05:35 AM
#6
Re: Clarify me on this example
Hi, If we do this way, i mean removing the delete statement, is it not going to be a memory leak problem ?
-
September 26th, 2008, 05:48 AM
#7
Re: Clarify me on this example
No.
The CCar object is created within the body of 'main' and destroyed when it goes out of scope, automatically.
"It doesn't matter how beautiful your theory is, it doesn't matter how smart you are. If it doesn't agree with experiment, it's wrong."
Richard P. Feynman
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|