C + +-derived classes cast to base class

Source: Internet
Author: User

derived classes cast to base class


This address: http://blog.csdn.net/caroline_wendy/article/details/24268821


in the case of polymorphic use, A pointer to a derived class or a reference to a pointer or reference that can be converted to a base class, that is, pointer to base class can point to base class part of a derived class ;

base* B = derived* D;

B and D point to the content is equal , b = = d, because there is an implicit conversion between b = = (base*) D;

the addresses of B and d are different int (b)! = Int (d), because B points to the base class part of D, and D points to the complete derived class;

But assuming the stealth conversion , int (b)! = Int ((base*) d), the address is the same.


The code is as follows:

/* * test.cpp * *  Created on:2014.04.21 *      author:spike *//*eclipse CDT, gcc 4.8.1*/#include <iostream>clas s A {int m_na;}; Class B {int m_nb;}; Class C:public A, public B {int m_nc;}; int main (void) {c* pc = new C; b* PB = pc;if (PC = pb) {std::cout << "equal" << Std::endl;} else {std::cout << "not Equal" << St D::endl;} if (int (PC) = = Int (pb)) {std::cout << "equal" << Std::endl;} else {std::cout << "not equal" << std :: Endl;}  if (int (PC) = = Int ((c*) pb) {std::cout << "equal" << Std::endl;} else {std::cout << "not Equal" << Std::endl;} return 0;}

Output:

Equalnot equalequal





C + +-derived classes cast to base class

Related Article

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.