C + +: derived class cast to base class

Source: Internet
Author: User

When used in polymorphism, a pointer or reference to a derived class can be converted to a pointer or reference to a base class, where a pointer to a base class can point to the base class part of a derived class;

base* B = derived* D;

B and D point to the same content, 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 portion of D, and D points to the complete derived class;

However, if 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>  
      
class 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" < < Std::endl;  
    }  
      
    if (int (PC) = = Int (pb)) {  
        std::cout << "equal" << Std::endl;  
    } else {  
        std::cout << "Not E Qual "<< Std::endl;  
    }  
      
    if (int (PC) = = Int ((c*) pb)) {  
        std::cout << "equal" << Std::endl;  
    } else {  
        std::cout << "n OT equal "<< Std::endl;  
    }  
      
    return 0;  
}

Output:

Equal not  
equal  
equal

Author: csdn Blog spike_king

More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/

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.