OOP-related type conversions in C + +

Source: Internet
Author: User

As we all know, there are many types of conversions in C + +. Today, we do not discuss the type conversions of ordinary variables (such as int into double, etc.). This article mainly discusses object-oriented type conversions: up and down conversions.

First, we define a base class base and inheriting class derived, with the following code:

// Base.h class base{    public:    int  i;    Base ();     void func1 ();     Virtual void Func2 ();     Virtual  ~Base ();}
// Derived.h class  Public base{    public:    int  i;    Derived ();     void func1 ();     Virtual void Func2 ();     virtual ~Derived ();}
//Derived.cppDerived::D erived () {cout<<"Constructor Derived"<<Endl;}voidderived::func1 () {cout<<"Derived func1"<<Endl;}voidDerived::func2 () {i=3; cout<<"Derived Func2"<<Endl;}
 // base.cpp   = 1  ; cout  << base Constructor  Span style= "color: #800000;" > " <<ENDL;}  void   Base::func1 () {cout  << base func1   <<ENDL;}  void   Base::func2 () {cout  << base func2   <<endl;}  

Convert up: refers to the transformation of a subclass into a base class. That is: the conversion of derived to base.

down conversion: refers to the conversion of a base class to a subclass. That is, the conversion of base to derived.

At this point, we need to note that except for a special case (which we will say below), all upward and downward conversions refer to pointers or references to conversions, not ordinary objects !

First, here we briefly describe the static type and dynamic type of the variable (run-time type). Because of the introduction of OOP, there are two types of pointers or reference variables, the type that is marked when they are declared is the static type of the variable, and the actual type of the variable is the dynamic type when the program is run to, and the normal variable only has a static type.

It is precisely because there are two types of variables for pointers or reference variables, which can be simply understood as dynamic bundles, depending on how the actual type of runtime calls the corresponding virtual function. This is the basis for the realization of the polymorphic mechanism in OOP. If there are only ordinary variables, objects, there is no polymorphism (in C + +).

So we have the following code snippet, the way the subclass is converted to the parent class, the way the parent pointer is directed to the child class pointer, called up. The up-conversion is implicit conversion.

New*_pb = _PD;

The following code fragment, in which the parent class is converted to a subclass, refers to the way the child pointer points to the parent class, which is called a down conversion. A down conversion is a must cast. Moreover, the downward conversion of the way is a certain danger , the use of extreme caution!

*_PD = (derived*) &_oB;

Let's take a piece of code to understand the dynamic and static types of type conversions, and the danger of downward conversions.

1 //Main.cpp2 voidMain ()3 {4 5 Derived _od;6 Base _ob;7     8     //Segment 19Base *_PB1 = &_od;Ten_pb1->func1 (); One_pb1->Func2 (); Acout << _pb1->i <<Endl; -cout <<Endl; -  the     //Segment 2 -Derived *_PD1 = (derived*) &_ob; -_pd1->func1 (); -_pd1->Func2 (); +cout << _pd1->i <<Endl; -  +}

In Segment1, we are converting upward, and the output is as follows:

Since func1 is a normal function, this is determined at compile time, called by the static type of the variable, which is called Base func1 (), and Func2 is a virtual function, run-time binding, based on the actual dynamic type of runtime calls, run-time _ PB1 is already bound to a derived type object, so Func2 () in derived is called, and the last variable i is also determined by the static type.

In Segement2, we perform a downward conversion and the output is as follows:

Since func1 is a normal function, this is determined at compile time, called by the static type of the variable, called Derived's func1 (), and Func2 is a virtual function, run-time binding, based on the actual dynamic type of runtime calls, run-time _ PD1 is already bound to a base type object, so at this point the Func2 () in base is called.

The value of the variable I here needs to be discussed, because the value of the variable i is also determined according to the static type, so it should be the value of the variable I in derived, because I was initially not initialized in the constructor of derived, so its value is undefined chaotic value. At this time, the careful students must be the main, we in the derived of the FUNC2 variable I of the value of the changes, but does not seem to have the effect. This is because FUNC2 is a virtual function, at which point the _PD1 call is the FUNC2 function in base, so it modifies the corresponding value of I in the base domain, and I at the end of the output is still determined by the static type of the variable, and the output is still I in the derived domain, which is still uninitialized. This is also what we mentioned earlier, why there is a certain risk of forcing downward conversions.

Introduction of Dynamic_cast

However, we all know that in the actual project is to involve downward conversion, then there are so many dangers how to deal with. Dynamic_cast<type> () was introduced in C + +. It determines whether a downward conversion is possible by judging whether the run-time type of two variables is the same at the time of execution to the statement. Suppose we have the following three classes of relationships.

class Geometry; class  Public Geometry; class  Public Geometry;

So, we can write this in the method:

void dosomething (Geometry *_pigeom) {    if(dynamic_cast<line*>(_PIGEOM))        ...         // Do something for line type    Else if (dynamic_cast<curve*>(_pigeom))          ... // Do something for Curve type}

This avoids the creation of undefined behavior, and the corresponding requirements can be achieved.

Upward-converted cut (Slice)

Finally, back to what we started with, we said that except for a special case (as we'll say below), all upward and downward conversions refer to pointers or references to conversions, not ordinary objects. The up conversion can also be applied between objects, as follows:

= _od;

At this point, the equivalent of using the parent class portion of the subclass object to initialize the parent class object is actually a cut .

OOP-related type conversions in C + +

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.