Interview Questions: use C to simulate the polymorphism of C ++

Source: Internet
Author: User

There are two C ++ classes:

Class base {

Public:

Base (int A, int B): M_a (A), m_ B (B ){}

Virtual void func1 ();

Virtual int func2 ();

PRIVATE:

Int M_a, m_ B;

}

Class derived: public base {

Public:

Derived (int A, int B, double D): Base (a, B), m_d (d ){}

Virtual int func2 ();

PRIVATE:

Double m_d;

}

Simulate the implementation mechanism of the C ++ compiler, use the C language to define the base and derived, and implement the Code for creating two classes.

========================================================== ======================================

Typedef void ** vtblptr; // combine the meaning

Struct base_t

{

Vtblptr _ vtbl;

Int M_a;

Int m_ B;

};

Struct derived_t

{

Vtblptr _ vtbl;

Int M_a;

Int m_ B;

Double m_d;

};

New Base

Base_t * pbase = malloc (sizeof (base_t ));

Pbase-> _ vtbl [0] = & _ base_t_func1;

Pbase-> _ vtbl [1] = & _ base_t_func2;

_ Base_t_base (pbase, a, B); // It is said that the constructor does not need this?

New derived

Derived_t * pderived = malloc (sizeof (derived_t ));

Pderived-> _ vtbl [0] = & _ base_t_func1;

Pderived-> _ vtbl [1] = & _ derived_t_func2;

Derived_t Constructor

Void _ derived_t_derived (derived_t * pderived, int A, int D)

{

_ Base_t_base (base_t *) pderived, A, B );

Pderived-> m_d = D;

};

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.