Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

The Construction of Top-level parent Class (5)

Shulou Source: shulou.com Published: 2022-06-03 04:35:31 09月15日 Update

In contemporary software architecture practice, we have three principles: 1, try to use single inheritance for system design; 2, try to keep only a single inheritance tree in the system; 3, try to use combinatorial relationships instead of inheritance relationships. However, due to the flexibility of C++ language, there can be multiple inheritance trees in the code, and the difference of C++ compilers makes the same code may behave differently.

Let's think about what happens if the new operation fails. Then it will definitely cause an exception. Then we use the exception class we built earlier. At this time, we only need to throw an exception that is out of memory and we will get a hint. It is now necessary to create a top-level parent class, so what is the point of creating it? One is to follow the classical design criteria, all the data structures are inherited from the Object class, and the other is to define the behavior of dynamic memory request to improve the portability of the code. Let's take a look at the interface definition of the top-level parent class, as follows

Class Object {public: void* operator new (unsigned int size) throw (); void operator delete (void* p); void* operator new [] (unigned int size) throw (); void operator delete [] (void* p); virtual ~ Object () = 0;}

Let's take the code as an example to experiment.

Object.h source code

# ifndef OBJECT_H#define OBJECT_Hnamespace DTLib {class Object {public: void* operator new (unsigned int size) throw (); void operator delete (void* p); void* operator new [] (unsigned int size) throw (); void operator delete [] (void* p); virtual ~ Object () = 0;};} # endif / / OBJECT_H

Object.cpp source code

# include "Object.h" # include # include using namespace std;namespace DTLib {void* Object::operator new (unsigned int size) throw () {cout

Tags: Pointers objects top-level functions source code code subclasses behavior memory guidelines intelligence portability customization creation development migration design that is information dynamic Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL OPPO Reno Xiaomi Apple NVidia