C ++-Explanation of Polymorphism

Source: Internet
Author: User
#include <iostream>
#include<stdio.h>using namespace std;class B{public:    void vf()    {        cout << "This is class B" << endl;    }};class D: public B{public:    void vf()    {        cout << "This is class D" << endl;    }};int main(){    B b, *pb;    D d, *pd;    pb = &b;    pb->vf();    printf("%X\n",pb);    pb = &d;    pb->vf();        // no cast needed    printf("%X\n",pb);    pd = (D*)&b;    pd->vf();    // must cast explicitly    printf("%X\n",pd);    pd = &d;    pd->vf();    printf("%X\n",pd);    return 0;}/***** result *******//*This is class B22FF17This is class B22FF16This is class D22FF17This is class D22FF16*/

It is only related to the pointer (type) pd-> vf () and the pointer pd.

/***** The call to a virtual function is determined by the pointer/reference value (Runtime polymorphism) *****/# include <iostream> using namespace std; class B {public: void virtual vf () {cout <"This is class B" <endl ;}; class D: public B {public: void vf () {cout <"This is class D" <endl ;}; int main () {B B, * pb; D d, * pd; pb = & B; pb-> vf (); pb = & d; pb-> vf (); pd = (D *) & B; pd-> vf (); pd = & d; pd-> vf (); return 0 ;} /******* result ******/* This is class BThis is class DThis is class BThis is class D */

#include <iostream>using namespace std;class B{  // virtual function in base class must be defined or be pure  // unless the base class and all its derived classes are not instantiated  public: void virtual vf();};class D: public B{  public: void vf() { cout << "This is class D" << endl; }};main(){  D d, *pd;}/*** result ***//*ERRORundefined reference to `vtable for B'*/

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.