Boost: polymorphic_cast usage

Source: Internet
Author: User

 

Boost: polymorphic_cast is used to implement down cast. If the conversion fails, an exception is thrown.

 

This is similar to dynamic_cast. However, if the dynamic_cast pointer fails to be converted, no exception is thrown.

 

The following is an example of the two:

 

 

# Ifndef base_for_cast

# Define base_for_cast

 

# Include <iostream>

# Include <boost/cast. HPP>

# Include <boost/scoped_ptr.hpp>

 

Class base1

{

Public:

Virtual void print ()

{

STD: cout <"base1: Print" <STD: Endl;

}

 

Virtual ~ Base1 (){}

Protected:

PRIVATE:

};

 

 

Class base2

{

Public:

Void only_base2 ()

{

STD: cout <"only base2" <STD: Endl;

}

 

Virtual ~ Base2 (){}

Protected:

PRIVATE:

};

 

 

Class derived: Public base1, public base2

{

Public:

Void print ()

{

STD: cout <"derived: Print" <STD: Endl;

}

 

Void only_here ()

{

STD: cout <"only derived 2" <STD: Endl;

}

 

Void only_base2 ()

{

STD: cout <"derived base2" <STD: Endl;

}

~ Derived () {STD: cout <"derived destuctor" <STD: Endl ;}

};

 

Void test_polymorphic_cast ()

{

Base1 * P1 = new derived;

 

Boost: scoped_ptr <base1> BSP (P1 );

P1-> Print ();

 

Try

{

Derived * Pd = boost: polymorphic_cast <derived *> (P1 );

Pd-> only_base2 ();

Pd-> only_here ();

 

Base2 * PBS = boost: polymorphic_cast <base2 *> (P1 );

PBS-> only_base2 ();

}

Catch (STD: bad_cast & E)

{

STD: cout <E. What () <STD: Endl;

}

}

 

Void polyporphic_cast_example (base1 * P)

{

Derived * D = boost: polymorphic_cast <derived *> (P );

D-> Print ();

 

Base2 * b2 = boost: polymorphic_cast <base2 *> (P );

B2-> only_base2 ();

}

 

The above code is compiled and tested through vs2008. Note that the boost library path is set.

 

 

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.