C + + ' dynamic_cast ' and Java ' instanceof ' usage comparison

Source: Internet
Author: User

In Java, if a is a base class and B is a derived class, then instanceof can be used to determine whether an instance object is a or B, which is equivalent to a two-dollar operator, but with the = =, A, <, the difference is that it is made up of letters and is a reserved word for Java. But in C + + there is no such keyword, but we can use dynamic_cast to achieve the same functionality, see the following code:

Java ' instanceof '

//Java ' instanceof ' Public classA {// ...} Public classBextendsA {// ...} Public classCextendsA {// ...} Public voidprocess (a a) {if(AinstanceofB) {//Process B    }    if(a instanceof C) {//Process C    }}

C + + ' dynamic_cast '

//C + + ' dynamic_cast 'classA {// ...}classB: PublicA {// ...}classC: PublicA {// ...}voidProcess (A *a) {if(B *b = dynamic_cast<b*>(a)) {//Process B    }    if(C *c = dynamic_cast<c*>(a)) {//Process C    }}

C + + ' dynamic_cast ' and Java ' instanceof ' usage comparison

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.