Dynamic binding for C + + virtual functions

Source: Internet
Author: User

C + + Specifies that function dynamic binding needs to be implemented using virtual functions. The specific implementation is: Dynamic linking uses the object's reference or the object's pointer to manipulate the virtual function , but if the object is used to manipulate the virtual function, it still uses the static-linked method.

#include <iostream>using namespace std;class a{public:virtual void printa () {cout << "A:printa ()" <<endl;}}; class b :p Ublic a{public :virtual  void printa () {cout<< "B:printA ()" <<endl;}}; Void printab (A&NBSP;&AMP;AA) {Aa.printa ();} Int main () {    a a= a ();     b b= b ();     A *pab=b;//pab  represents a pointer   is a a  type   but points to a Class B object    // b  *pba=a;   If you do not annotate   will error &nbsp, because you can only use the parent class pointer   objects that point to subclasses, and the child class                    //   pointers cannot point to objects of the parent class          pab->printa ()///By using the object's pointer   to use the   virtual function for dynamic linking, the result will be   B:printa ()     //can also be used with   for operations            a &aa = b;&nbSp;    printab (AA);//The effect is the same as the  aa.printa ()     is   executed  b:printa ();          return 0;}



The fact that there is a dynamic linking to this pattern is because the project manager defines the actions of the parent class, and the employee needs to implement the implementation of the corresponding action in the parent class in the specific subclass, rather than using the action of the parent class, so the result of the dynamic union is basically a pointer to the parent class or a reference To point to or refer to the object of the subclass to achieve the purpose of the subclass operation.

This article is from the "xingnallu" blog, make sure to keep this source http://781588100.blog.51cto.com/9429625/1559681

Dynamic binding for C + + virtual functions

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.