virtual function (constructor + destructor)

Source: Internet
Author: User

The constructor cannot be a virtual function. When you create a derived class object, the constructor of the derived class is called instead of the constructor of the base class, and then the constructor of the derived class uses a constructor of the base class, which differs from the inheritance mechanism.

Therefore, a derived class does not inherit the constructor of a base class, so declaring a class constructor as a virtual function is meaningless.

The destructor should be a virtual function, unless the class does not use the base class.

The default is called "Static binder."

//HeritedDerived.cpp:Defines the entry point for the console application.//#include"stdafx.h"#include"stdio.h"#include<iostream>using namespacestd;classfather{ Public: Father () {cout<<"I am father!\n"; }    Virtual~Father () {cout<<"This is father ' s destructor!\n";        Compare (); }    Virtual voidOutput () {cout<<"This was a debug function in father\n"; }    Virtual voidCompare () {cout<<"This was another virtual function in father\n"; }    };classSon: Publicfather{ Public: Son () {cout<<"I am son!\n"; M_pint=New int[ +]; }    ~Son () {cout<<"This is son ' s destructor!\n"; if(NULL! =m_pint) {            Delete[] m_pint; M_pint=NULL; cout<<"Memory Release successfully!\n";    } Compare (); }    Virtual voidOutput () {cout<<"This was a debug function in son\n"; }    Virtual voidCompare () {cout<<"This was another virtual function in son\n"; }Private:    int*M_pint;};int_tmain (intARGC, _tchar*argv[])    {Father Father;    Son son; Son.    Output (); Father*father1 =NewSon; Father1-Output (); DeleteFather1; return 0;}

}

You should typically provide a virtual destructor to the base class, even if it does not require a destructor.

Constructors and destructors cannot invoke other virtual functions, even if they are called, they lose the meaning of virtual functions. The object dynamic generation mechanism of C + +.

virtual function (constructor + destructor)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.