Research on Virtual Functions

Source: Internet
Author: User

1> 〉

Class {
Public:
Virtual void F () {cout <"A: F" <Endl ;};
};

Class B: Public {
Public:
Virtual void F () {cout <"B: F" <Endl ;};
};
Class C: Public {
Public:
Virtual void F () {cout <"C: F" <Endl ;};
};
Void test (A * ){
A-> F ();
};
Int main (INT argc, char * argv [])
{
B * B = new B;
C * c = new C;
Char choice;
Do {
Cout <"type B for Class B, C for Class C:" <Endl;
Cin> choice;
If (choice = 'B '')
Test (B );
Else if (choice = 'C '')
Test (C );
} While (1 );
Cout <Endl;
Return 0;
}
Output result:

B: F

C: F

Conclusion: Test (A * A) actually has an implicit conversion process from an inherited class pointer to a base class pointer. We can see that using the virtual function, we can call the inheritance class function in the base class. If it is not a virtual function, the inherited class pointer can only call the base class function after being converted to the base class pointer. Conversely, if the base class pointer is converted to the inherited class pointer, it can only display the conversion. After the conversion, the inherited class pointer can call the base class and the inherited class pointer.

 

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.