About the polymorphism of C + +

Source: Internet
Author: User

Not long ago, a bit of Jinshan, one side more smoothly. Two face when the interviewer mainly asked the question of C + +, seemingly the answer is not good, and then asked about the problem of polymorphism, let me describe, or write an example out, I was 2, so review it here.
Polymorphic, literally means "multiple states". In OOP (object-oriented), many different implementations of interfaces are polymorphic. Polymorphism is a technique that allows you to set a parent object to be equal to one or more of his child objects, and after the assignment, the parent can operate differently depending on the attributes of the child object that is currently assigned to it. Simply put, it is: allows pointers of subtypes to be assigned to a pointer of the parent type.
In C + +, the implementation of polymorphism has the following methods: virtual function, abstract class, rewrite, overwrite, template.
I'm going to implement a virtual function first.

#include <iostream>using namespace Std;class a{public:a () {}~a () {}virtual void fun () {cout<< "This is A" < <endl;}}; Class B:public A{public:b () {}~b () {}void fun () {cout<< "This is B" <<endl;}}; int main () {A *a = new A (); A *b = new B (); A->fun (); B->fun (); if (a = null) Delete a;if (b! = null) delete B;return 0;}

The results of the operation are as follows:






About the polymorphism of C + +

Related Article

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.