Call between virtual and non-virtual functions between parent class and subclass

Source: Internet
Author: User

# Include <iostream> using namespace STD; Class A {public: A () {cout <"A" <Endl ;}~ A () {} virtual void func1 () {cout <"only in a" <Endl;} virtual void func2 () {cout <"virtual in a" <Endl;} void func3 () {cout <"non virtual in a" <Endl ;}}; Class B: public A {public: B () {cout <"B" <Endl ;}~ B () {} void func2 () {cout <"virtual in B" <Endl;} void func3 () {cout <"non virtual in B" <Endl ;}; int main () {B * B = new B (); A * A = (*) b; B-> func1 (); B-> func2 (); B-> func3 (); A-> func1 (); A-> func2 (); a-> func3 (); getchar (); Return 0 ;}

Output result:

1. Before creating a subclass to call the constructor of the subclass, the constructor of the parent class is called.
2. Virtual is related to polymorphism. A function with the virtual keyword is added. When calling a function, if the subclass has one, The subclass is called first. If the subclass does not exist, the function of the parent class is called.
3. When the parent class Pointer Points to a subclass object, if the called function exists in the parent class and the subclass, but it is not a virtual function in the parent class, whether it is a virtual function in the subclass. When called using the parent class pointer, the function in the parent class is executed instead of the function in the subclass. When called using the subclass pointer, the function in the subclass is executed.

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.