I understand that I have virtual
attached to the constructor or other function,
I don't know why virtual
is used for extinction.
When an object disappears, it automatically calls for an inherited class, right?
But what's the point of writing virtual
?
The virtual extinction is useful when base class pointer
points to the derived class
instance and delete
.
class Base{
public:
~Base() {
cout << "Base destructor!" << endl;
}
};
class Derived : public Base{
public:
char* largeBuffer;
Derived() {
largeBuffer = new char[3000];
}
~Derived() {
cout << "Derived destructor!" << endl;
delete[] largeBuffer;
}
};
The above code did not set the extinction of base
to virtual
.
In this situation, do the following codes 1 and 2 do the same thing?
int main(){
//Code1
cout << "---Derived* der1 = new Derived()---" << endl;
Derived* der1 = new Derived();
delete der1;
//Code2
cout << "\n\n---Base* der2 = new Derived()---" << endl;
Base* der2 = new Derived();
delete der2;
}
Results)
---Derived* der1 = new Derived()---
Derived destructor!
Base destructor!
---Base* der2 = new Derived()---
Base destructor!
In the case of Code 1, as you said, the extinction of Driven class
will call the extinction of Base Class
on its own.
That's why the buffer was successfully deleted.
However, Derived destructor
was not called in the case of code 2.
The buffer will not be delete
and will remain somewhere.
The Base
pointer points to an instance of the Derived
class
This is because members of Derived
are not accessible
The virtual destructor is used to prevent memory from leaking in this situation.
class Base{
public:
virtual ~Base() {
cout << "Base destructor!" << endl;
}
};
If Base
extinction is set to virtual
,
Now, even in the case of Code 2, the extinction of Derived class
is called
Memory is released normally.
© 2024 OneMinuteCode. All rights reserved.