Virtual functions are called by the constructor and member functions of the class

  • 2020-04-01 21:33:50
  • OfStack


#include<iostream>
class base{
public:
    base()
    {
        std::cout<<std::endl;
        std::cout<<"base constructor"<<std::endl;
        func1();
        std::cout<<std::endl;
    }
    virtual ~base()
    {
        std::cout<<std::endl;
        std::cout<<"base distructor"<<std::endl;
        func1();
        std::cout<<std::endl;
    }
    virtual void func1()
    {
        std::cout<<"base virtural func1"<<std::endl;
    }
    void func2()
    {
        std::cout<<"base member func2"<<std::endl;
        func1();
        std::cout<<std::endl;
    }
};
class derived:public base{
public:
    derived()
    {
        std::cout<<std::endl;
        std::cout<<"derived constructor"<<std::endl;
        func1();
        std::cout<<std::endl;
    }
    virtual ~derived()
    {
        std::cout<<std::endl;
        std::cout<<"derived distructor"<<std::endl;
        func1();
        std::cout<<std::endl;
    }
    virtual void func1()
    {
        std::cout<<"derived virtual func1"<<std::endl;
    }
};
int main()
{
    base *point = new derived();
    point->func2();
    delete point;
    return 0;
}

There will be output like this

< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201302/2013218114851252.jpg" >
Even if func1 is a virtual function, func1 is called in the constructor and destructor of the base class and derived class.

But func2, the normal member function, calls func1, and it goes through the flow of the virtual function.


Related articles: