Virtual functions in C + +

Source: Internet
Author: User

Code:

1#include <iostream>2#include <cstring>3 4 using namespacestd;5 6 classbase{7      Public:8         Virtual voidfunc1 ();9         Virtual voidFunc2 ();Ten         voidfunc3 (); One         voidFunc4 (); A }; -  - voidbase::func1 () { thecout<<"Base func1"<<Endl; - } -  - voidBase::func2 () { +cout<<"Base Func2"<<Endl; - } +  A voidbase::func3 () { atcout<<"Base func3"<<Endl; - } -  - voidBase::func4 () { -cout<<"Base Func4"<<Endl; - } in  - classDerived1: Publicbase{ to      Public: +         voidFunc1 ();//virtual can omit -         //Char Func2 () {}; Error, virtual function return type needs to be consistent the         voidfunc3 (); *         CharFunc4 (); $ };Panax Notoginseng  - voidderived1::func1 () { thecout<<"Derived1 func1"<<Endl; + } A  the voidderived1::func3 () { +cout<<"Derived1 func3"<<Endl; - } $  $ CharDerived1::func4 () { -cout<<"Derived1 Func4 can change the return type"<<Endl; - } the  - classDERIVED2: Publicbase{Wuyi      Public: the         voidfunc1 (); - }; Wu  - voidderived2::func1 () { Aboutcout<<"Derived2 func1"<<Endl; $ } -  - intMain () { -  ABase *B; + Derived1 De1; theB = &De1; -B->func1 (); $B->func3 (); theB->Func4 (); the De1.func4 (); the  theDERIVED2 *PDe2; -PDe2 = (derived2*) &De1; inPde2->func1 (); the  the     return 0; About  the}

Output:

Derived1 func1base func3base func4derived1 Func4 can change the return typeDerived1 func1

Summarize:

1, virtual function must be implemented in the parent class, do not implement can use pure virtual function;

2. The return type of a subclass virtual function must be the same as the return type in the parent class, and the normal function can be different;

3, subclass virtual function if the parameter changes, the virtual attribute disappears.

Virtual functions in C + +

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.