09. Virtual Destructor
HomeDesign PatternC++

09. Virtual Destructor

Static and dynamic destructor of derived class.

07. Prototype Pattern
06. LSP
05. Virtual Function

DesignPattern

Usage

  • Deletes a derived class instance by base class pointer

Explain

By using LSP, a base class pointer can handle its any child class' instances. However, it does not work as what we expect. Code 1 shows what problem is.

// 01_C_NormalDestructor.cpp
#include <iostream>
using namespace std;

class BaseClass
{
public:
    ~BaseClass() {};
};

class DerivedClass : public BaseClass
{
public:
    DerivedClass()
    {
        cout << "Resource allocated" << endl;
    }

    ~DerivedClass()
    {
        cout << "Resource released" << endl;
    }
};

int main()
{
    BaseClass* p = new DerivedClass;

    delete p;
}
// Compile: clang++ -std=c++14
//              -o 01_C_NormalDestructor 01_C_NormalDestructor.cpp
C++
Code 1. Deleting derived class instance by base class pointer
Resource allocated

As a result, DerivedClass instance is not deleted in Code 1. Because destructor of BaseClass is not inherited in DerivedClass, compiler does not call destructor of DerivedClass for delete. Only, compiler calls destructor of the type of the pointer.

To delete DerivedClass instance, there are two ways, static or dynamic.

The first way is static, which uses static_cast. Code 2 shows how it works.

// 02_C_StaticDestructor.cpp
#include <iostream>
using namespace std;

class BaseClass
{};

class DerivedClass : public BaseClass
{
public:
    DerivedClass()
    {
        cout << "Resource allocated" << endl;
    }

    ~DerivedClass()
    {
        cout << "Resource released" << endl;
    }
};

int main()
{
    BaseClass* p = new DerivedClass;

    delete static_cast<DerivedClass*>(p);
}
// Compile: clang++ -std=c++14
//              -o 02_C_StaticDestructor 02_C_StaticDestructor.cpp
C++
Code 2. Static deleting derived class instance with static_cast
Resource allocated
Resource released

Instead of using the pointer, we cast it to DerivedClass with static_cast. By using static_cast, p is changed to the pointer of DerivedClass in compile time, and delete will destruct DerivedClass instance. Because casting is done in compile time, it is faster than next. However, developer takes all responsibility for this casting.

The second way is to add Virtual Destructor to BaseClass. Code 3 is about Virtual Destructor.

// 03_C_VirtualDestructor.cpp
#include <iostream>
using namespace std;

class BaseClass
{
public:
    virtual ~BaseClass() {}
};

class DerivedClass : public BaseClass
{
public:
    DerivedClass()
    {
        cout << "Resource allocated" << endl;
    }

    ~DerivedClass()
    {
        cout << "Resource released" << endl;
    }
};

int main()
{
    BaseClass* p = new DerivedClass;

    delete p;
}
// Compile: clang++ -std=c++14
//              -o 03_C_VirtualDestructor 03_C_VirtualDestructorvv.cpp

C++
Code 3. Dynamic deleting derived class instance with virtual destructor
Resource allocated
Resource released

By using Virtual Destructor, delete can find the destructor of DerivedClass in run time. It is slower than the static way, because it takes time to find DerivedClass in run time. Also, we call it dynamic binding.

The default strategy of C++ compiler is static binding, which means compiler decides as much as it can in compile time. So, in compile time, compiler can optimize its output. However, dynamic binding is done in run time, so compiler cannot optimize it and needs to make some something helpful to find target instance and bind the target. It takes more cpu power compared to static binding. However, dynamic binding gives developer freedom to adapt runtime circumstance.

Summary

  • If an application is based on LSP, be careful to delete an instance.
  • Casting and Virtual Desctuctor is solutions for deleting derived class instance.
  • Static binding is faster, but dynamic binding is changeable.
Name

0 weights,1,abstract class,1,active function,3,adam,2,Adapter,1,affine,2,argmax,1,back propagation,3,binary classification,3,blog,2,Bucket list,1,C++,11,Casting,1,cee,1,checkButton,1,cnn,3,col2im,1,columnspan,1,comboBox,1,concrete class,1,convolution,2,cost function,6,data preprocessing,2,data set,1,deep learning,31,Design Pattern,12,DIP,1,django,1,dnn,2,Don't Repeat Your code,1,drop out,2,ensemble,2,epoch,2,favicon,1,fcn,1,frame,1,gradient descent,5,gru,1,he,1,identify function,1,im2col,1,initialization,1,Lab,9,learning rate,2,LifeLog,1,linear regression,6,logistic function,1,logistic regression,3,logit,3,LSP,1,lstm,1,machine learning,31,matplotlib,1,menu,1,message box,1,mnist,3,mse,1,multinomial classification,3,mutli layer neural network,1,Non Virtual Interface,1,normalization,2,Note,21,numpy,4,one-hot encoding,3,OOP Principles,2,Open Close Principle,1,optimization,1,overfitting,1,padding,2,partial derivative,2,pooling,2,Prototype,1,pure virtual function,1,queue runner,1,radioButton,1,RBM,1,regularization,1,relu,2,reshape,1,restricted boltzmann machine,1,rnn,2,scrolledText,1,sigmoid,2,sigmoid function,1,single layer neural network,1,softmax,6,softmax classification,3,softmax cross entropy with logits,1,softmax function,2,softmax regression,3,softmax-with-loss,2,spinBox,1,SRP,1,standardization,1,sticky,1,stride,1,tab,1,Template Method,1,TensorFlow,31,testing data,1,this,2,tkinter,5,tooltip,1,Toplevel,1,training data,1,vanishing gradient,1,Virtual Copy Constructor,1,Virtual Destructor,1,Virtual Function,1,weight decay,1,xavier,2,xor,3,
ltr
item
Universe In Computer: 09. Virtual Destructor
09. Virtual Destructor
Static and dynamic destructor of derived class.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgXvUavVsX4rYm8cgKQ8rzps7pHmmEVtkIb66G2o5KZFCfjvO96SCEUdaw_DMYzSbdVrB8XvnaKN8ljEE7EBjutI2XvsBL-2BLdijjJRIpAOEpvlhOW-hfWP3ir3wbE488AwdFEu7WKbLgO/s0/
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgXvUavVsX4rYm8cgKQ8rzps7pHmmEVtkIb66G2o5KZFCfjvO96SCEUdaw_DMYzSbdVrB8XvnaKN8ljEE7EBjutI2XvsBL-2BLdijjJRIpAOEpvlhOW-hfWP3ir3wbE488AwdFEu7WKbLgO/s72-c/
Universe In Computer
https://kunicom.blogspot.com/2018/04/09-virtual-destructor.html
https://kunicom.blogspot.com/
https://kunicom.blogspot.com/
https://kunicom.blogspot.com/2018/04/09-virtual-destructor.html
true
2543631451419919204
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago 1 minutes ago 1 hour ago 1 hours ago Yesterday 1 days ago 1 weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy