Reputation: 492
I have this simple code in a file called virtual.cpp
:
#include <iostream>
class Parent
{
public:
virtual ~Parent(){ std::cout << "Parent Destructor" << std::endl; }
virtual void VirtualFunction()
{
std::cout << "VirtualFunctionInParent" << std::endl;
}
};
class Child: public Parent
{
public:
virtual ~Child() { std::cout << "Child Destructor" << std::endl; }
virtual void VirtualFunction()
{
std::cout << "VirtualFunctionInChild" << std::endl;
}
};
int main()
{
Child child1;
Parent *parent1 = &child1;
delete parent1;
}
It compiles correctly
g++ -Wall --pedantic -o virtual virtual.cpp
But when I run it, I obtain this error:
./virtual
Child Destructor
Parent Destructor
free(): invalid pointer
Annullato (core dump creato)
I think it is due to the fact that I delete the pointer parent1, so this erases the memory to which the pointer point, namely &child1
.
So, when child1 goes out of scope, the Child destructor try to deallocate memory which no longer exists.
My questions:
Upvotes: -1
Views: 375
Reputation: 197
To answer your question more specifically
You are never going out of scope because you are declaring variables to the current stack frame in main(). In order to declare the variable to the heap (out of scope), you have to use dynamic memory allocation.
Parent * parent1 = new(Child);
delete(parent1);
What this code is doing is creating a child class in heap and then creating a parent1 pointer local to the scope that effectively points to the child class.
Upvotes: 1
Reputation: 461
First thing is the fact that you don't use new
or any other way to allocate the dynamic memory. So there is no point to use delete
.
To answer your next questions you must first tell us why do you want to create the parent pointer on address of the child?
Upvotes: 1
Reputation: 63745
I delete the pointer parent1, so this erases the memory to which the pointer point. Is my reasoning correct?
No. You are getting a core dump from your delete.
Only addresses returned from new
may be passed to delete
.
delete
does not erase memory, as memory has no concept of an "erased" state.
which is the correct way to handle this "going out of scope" situation?
Remove the delete
line. It is not necessary.
Any variable created within a scope is automatically managed when that scope is left.
Upvotes: 3
Reputation: 182753
Don't call delete
on an object you didn't allocate with new
. This object will be deleted when it goes out of scope, so there's nothing special to do to destroy it properly.
When you want objects to start their lifetime inside a scope and end their lifetime when the scope ends, don't use new
and delete
. Just declare them normally.
Use new
and delete
for objects whose lifetimes you want to manage. Allocate them with new
and call delete
when you are done with them.
Upvotes: 1