Reputation: 161
MainClass *mb[1];
Class1 *m1;
cout << "Constructor type (1 - no parameters || 2 - with parameters): ";
int choose;
cin >> choose;
if (choose == 1) {
mb[1] = new Class1;
}
else if (choose == 2) {
mb[1] = new Class1("Red", 1);
}
m1 = dynamic_cast<Class*>(mb[1]);
m1->printEverything();
getchar();
and after that Windows 10 throws me "Program1.exe stopped working". Trying to add delete mb[1] , but no luck.
Destructor:
~Class() {
cout << endl;
getchar();
}
How can I delete derived class object?
Upvotes: 1
Views: 90
Reputation:
Deallocation should be done by:
delete mb[0]
You should use mb[0] to access first element of array
Upvotes: 1
Reputation: 3201
You need to store the object in mb[0]
(not mb[1]
) because array indexing is 0-based in C and C++ and you only reserved space for one element in mb
. Reading from or writing to mb[1] yields undefined behaviour in your program, typically resulting in a crash.
Deallocating your object must be done with delete mb[0]
. Not with delete[]
which is for deallocating memory allocated with new []
.
Upvotes: 1