Conversion between a C + + base class and a derived class

Source: Internet
Author: User

1#include <iostream>2#include <string>3 using namespacestd;4 classBox5 {6  Public:7     voidSetWidth (Doublewidth) {8          This->width=width;9     }Ten     voidSethieght (Doubleheight) { One          This->height=height; A     } -     voidgetwidth () { -cout<<width<<Endl; the     } - Private: -     DoubleWidth,height; - }; + classColorbox: Publicbox{ -  Public: +     voidSetColor (stringcolor) { A          This->color=color; at          -     } -     voidGetColor () { -cout <<color<<Endl; -     } -  in Private: -     stringcolor; to }; + intMain () { - Colorbox Colorbox; the box box; *Colorbox.setcolor ("Red"); $Colorbox.sethieght (Ten);Panax NotoginsengColorbox.setwidth (Ten); - Colorbox.getcolor (); the colorbox.getwidth (); +box=Colorbox; A box.getwidth (); the     //using pointers +Box *ptr; -ptr=&Colorbox; $cout<<ptr<<endl<<&box<<Endl; $Ptr->getwidth (); -Box &r1=box; -  the     //R1 and Box share the same piece of storage unit. You can also initialize a reference variable of a base class with a child class object -     //R1 and pointer types are different, box and box*Wuyi r1.getwidth (); theBox &r2=Colorbox; -     //derived class objects can be assigned or initialized to a reference to a base class object Wu     //However, you cannot call a data member of a subclass, at which point the base class reference is not an alias for the derived class object, nor does it share the same storage unit with the derived class.  -     //It is only the alias of the base class part of the derived class, and the base class reference shares the same storage unit with the base class part in the derived class. 0027f868 About     //0027f850 $ r2.getwidth (); -cout<<&r2<<endl<<&box<<Endl; -  -     return 0; A}

The transformation between a base class and a derived class, if the object of the base class wants to access the data member function of the subclass, it is going to be transformed.

Conversion between a C + + base class and a derived class

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.