Re-learning C + + (11) Oop object-oriented programming (2)

Source: Internet
Author: User
Tags function prototype

Transformations and inheritance

This section mainly needs to distinguish between:

    • Conversion of base classes and derived classes;

    • Conversions of references (pointers) and conversions of objects.

1. Each derived class object includes a base class part. So. The ability to perform operations on a derived class object as if it were a base class object.

Based on this, it is possible to convert a reference (pointer) of a derived class object to a reference (pointer) of a base class child object, and there is a self-initiated conversion.

Conversely, the base class does not exist for its own trespass to the derived class, so the base class does not include members of the derived type. Also, there are restrictions on binding a base-class pointer or reference to a derived class object, because the compiler cannot know that the conversion is safe at compile time (the compiler determines whether the conversion is legal, just the static type of the pointer or reference). Suppose we determine that the conversion of a base class to a derived class is secure, be able to use static_cast to force the compiler to convert, and be able to check at execution time with the dynamic_cast request.

2. Reference conversions are different from object conversions.

In the reference transformation. The object itself is not copied, and the transformation does not change the derived type object in any way.

In an object transformation (not a reference or pointer), the type of the parameter is fixed. When a derived class object is passed to a base class object, the base class portion of the derived class object is "copied" to the shape, where the base class object is initialized or assigned: the constructor is called when the value is initialized, and the assignment operator is called when the assignment is made. (In fact, the generic base class's copy constructor and the assignment operator's shape is a const reference to the base class type, because there is a conversion from the derived class reference to the base class reference, so these two member functions can be used to initialize or assign values from the derived class object to the base class object.)

Constructors and copy control constructors

Example 1:

public Item_base{public:    Bulk_item():min_qtydiscount(0.0) {}};

The constructor implicitly calls the base class's default constructor to initialize the base class part of the object: first initializes the Item_base section with Item_base's default constructor, initializes the members of the Bulk_item section, and executes the function body of the constructor.

Example 2:

public Item_base{public:    Bulk_item(const std::stringdouble sales_price, std::size_t qty=0double disc_rate=0.0):    Item_base(book, sales_price),min_qty(qty), discount(disc_rate) {}};

The constructor initializes the base class sub-object using the Item_base constructor with two parameters.

* Initialize the base class first. The members of the derived class are then initialized according to the declaration order.

* A class can only initialize its own "direct" base class.

Replication Control and inheritance

* Includes only class type or built-in type data members, classes without pointers generally have the ability to use compositing operations. The copying, copying or revocation of such members does not require special control.

Suppose a derived class defines its own copy constructor, which generally should "explicitly" initialize the base-class part of the object using the base-class copy constructor:

class Base {/* …… */};classpublic Base{public:    //Base::Base(const Base&) not invoked automatically    Derived(const Dervied& d):        /* other member initalization*/    {/* …… */}};

Base (d) converts the derived class object D to a reference to its base class part, and calls the base class copy constructor.

* Assume that base (d) is omitted. The base class portion of the object is initialized with the "default" constructor of base--not in line with our "copy" intent.

* For copy operators. You must prevent yourself from assigning values.

Derived &Derived::oprator=(const Derived &rhs){    if (this != &rhs)    {        Base::operator//assign the base part        //assign the derived part    }    return *this;}

The derived class destructor is not responsible for revoking the members of the base class object. The compiler always "explicitly" invokes the destructor of the base class part of the derived class object. Each destructor is only responsible for knowing its members:

public Base{public:    //Base::~Base() invoked automatically    ~Derived() {/* 清理派生类部分的成员 */}};

* The undo order of an object is reversed from the construction order: The derived class destructor is executed first. The base class destructor is then called up by the hierarchy of inheritance.

Virtual destructor

Be sure to perform the appropriate destructor. The destructor in the base class must be a virtual function:

class Item_base{    new Item_base;delete//调用Item_base的析构函数new//指针的静态类型和动态类型不同delete//调用Bulk_item的析构函数

In the above case. Suppose we don't define a virtual destructor. The second delete call will be a destructor for item_base, which is undefined for derived types.

* Constructors cannot be defined as virtual functions. Assigning an operation subscript character to a virtual function can be confusing and useless.

Virtual functions in constructors and destructors

First you need to understand:

When you construct a derived class object, the base class constructor is executed first, and the derived class part of the object is uninitialized.

Undoing a derived class object first revokes the derived class part.

In both cases, the object is incomplete.

Therefore, in a base class constructor or destructor, the compiler treats the derived class object "as a base class type Object."

Assume that a virtual function is called in a constructor or destructor. Executes the version number of the constructor or destructor itself type definition.

Reason:

Assuming that the derived class version number of a virtual function is called from a base class constructor, the derived class version number may invoke the derived member. At this point, the derived part of the object is not initialized yet!

This interview may cause the program to crash.

Class scope in case of inheritance

In the case of inheritance, the scope of the derived class is nested within the scope of the base class.

Assuming that the name cannot be determined in the scope of the derived class, the definition of that name is found in the perimeter base class scope.

A member of a derived class with the same name as a base class member will mask direct access to the base class member (access to the masked base class member via the scope operator).

Attention. for functions. Even if the function prototype is different. Just have the same name. Base class members are masked.

A function declared in a local scope does not overload a function defined in a global scope, and a function defined in a derived class does not overload a member defined in a base class.

Therefore, assume that the base class has the following function:

int memfcn();

The derived class has the following function:

int memfcn(int);

The call to MEMFCN () on the derived class will be an error. Therefore, there is no overload of the base class function, and MEMFCN () in the base class is masked.

This also explains why virtual functions must have the same prototype in both the base class and the derived class.

Look at the following code:

Class base{ Public:Virtual int FCN();}; Class D1: Publicbase{ Public:int FCN(int);//Shielding base class FCN ()};class D2: Publicd1{ Public:int FCN(int);//non-virtual function, shielded D1 FCN (int)    intFCN ();//virtual function, overriding the base class's FCN ()}; Base bobj;d1 d1obj;d2 d2obj; Base *BP1 = &bobj, *bp2 = &d1obj, *bp3 = &D2OBJ;BP1->FCN ();//call BASE::FCN at run timeBP2->FCN ();//call BASE::FCN at run timeBP3->FCN ();//call D2::FCN at run time

Three pointers are pointers to the base class type, so the three calls are determined by locating FCN in base.

Because FCN is a virtual function, the compiler generates code that is invoked at execution time based on the actual type that the reference or pointer binds to.

Pure virtual function

After the function table, write = 0 To specify a pure virtual function:

double fcn(stdconst0;

A class that contains one or more pure virtual functions is an abstract base class, except as part of an object that is a derived class of an abstract base class. You cannot create an object of an abstract type.

Containers and inheritance

Suppose a container holds an object of the base class type, and when a derived class object is inserted, the base class part of the derived class object is "copied" to the base class object and saved in the container (so the derived class part is cut off.) This means that the container can only be a base class object, not a derived class object.

One solution is to use a container to hold a pointer to an object.

Re-learning C + + (11) Oop object-oriented programming (2)

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.