Amazing use of dynamic_cast

Source: Internet
Author: User

 

Class base
{
Public:
Void Iam () {cout <"base \ n ";}
Virtual ~ Base (){}
};
Class derived: public Base
{
Public:
Void Iam () {cout <"derived \ n ";}
Virtual ~ Derived (){}
};

Void testclass (base * P)
{
// Try to output the actual class name here
// P may be a base pointer or a derived pointer.
}

 

 

 

The test cases are as follows:

Base B;
Derived D;
Testclass (& B );
Testclass (& D );

 

 

The output is:

Base

Derived

-- From 2kgames intern pen questions

 

In fact, a parent class and a subclass are given, and a pointer pointing to the class is created. Then, the pointer has been forcibly converted into a pointer pointing to the parent class, then you want to use some method to determine whether the object pointed to by the pointer is actually a real parent class object or a subclass object forced to be a parent class!

Use dynamic_cast to force type conversion. The following solutions are available:

 

Code

Solution # Include <iostream>

Using namespace STD;

Class base
{
Public:
Void Iam () {cout <"base \ n ";}
Virtual ~ Base (){}
};
Class derived: public Base
{
Public:
Void Iam () {cout <"derived \ n ";}
Virtual ~ Derived (){}
};

Void testclass (base * P)
{
// Try to output the actual class name here
// P may be a base pointer or a derived pointer.
If (derived * temp = dynamic_cast <derived *> (p ))
{
Temp-> Iam ();
}
Else
{
P-> Iam ();
}
}

Int main (INT argc, char * argv [])
{
Base B;
Derived D;
Testclass (& B );
Testclass (& D );
Return 0;
}

 

 

 

The output result displayed on vs2008 is:

Base

Derived

 

^_^!

 

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.