Example of C + + virtual function usage

Source: Internet
Author: User

PROGRAM1:
Class a{

Public

void print () {cout<< "This is A" <<ENDL;}

};

Class B:public a{

Public

void print () {cout<< "This is B" <<ENDL;}

};

int main () {

A;

b b;

A.print ();

B.print ();

}

Output:

This is A
This is B

PROGRAM2:
int main () {   //main2

A;

b b;

A * p1=&a;

A * p2=&b;

P1->print ();

P2->print ();

}

Output:

This is A
This is A

PROGRAM3:
Class a{

Public

virtual void print () {cout<< "This is A" <<ENDL;} Now it's a virtual function.

};

Class B:public a{

Public

void print () {cout<< "This is B" <<ENDL;} Do you need to add the keyword virtual to the front?

};

Output:
This is A
This is B



Dry:
If the child class overrides the virtual function of the parent class
A pointer to the parent class, or a reference to an object that actually points to the child class
When a virtual function is called through the pointer or reference, the (virtual) function of the subclass is called

If it is not a virtual function, the function of the parent class will be called

Example of C + + virtual function usage

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.