Inheritance and polymorphism in C + +

Source: Internet
Author: User

The inheritance and polymorphism in C + + is an important point to explain the characteristics of inheritance and polymorphism. Inheritance is a subclass of the use of the members of the base class and member functions, the way of inheritance is divided into public,protected and private, the main explanation today is polymorphic, polymorphic is the base class function must have virtual. And a pointer to the parent class that points to the child class object, for example:

#include <iostream>

#include <string>

using namespace Std;

//

Class A

{

Public

A ()

{

cout << "A ()" << Endl;

}

~a ()

{

cout << "~a ()" << Endl;

}

virtual void fun1 ()

{

cout << "a::fun1 ()" << Endl;

}

virtual void fun2 ()

{

cout << "a::fun2 ()" << Endl;

}

int A;

};

Class A1:public A

{

Public

A1 ()

{

cout << "A1 ()" << Endl;

}

~A1 ()

{

cout << "~a1 ()" << Endl;

}

virtual void fun1 ()

{

cout << "a1::fun1 ()" << Endl;

}

void Fun2 ()

{

cout << "a1::fun2 ()" << Endl;

}

int A1;

};

void Show (A *PB)

{

Pb->fun1 ();

}

int main ()

{

A;

A1 A1;

Show (&A1);

/*A1.FUN1 (); */

/*cout << sizeof (A1) <<endl;*/

GetChar ();

return 0;

}

A pointer to the parent class in the show function will produce a function of the parent class, and a pointer to the child class will produce a function of the subclass, which is polymorphic.

This article is from the "local and static variables" blog, so be sure to keep this source http://10810512.blog.51cto.com/10800512/1754279

Inheritance and polymorphism in C + +

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.