Inheritance and polymorphism in C + + (UP)

Source: Internet
Author: User

Inherited

1. Private inheritance: The public and protected members of the base class are private members of the derived class and cannot be accessed by subclasses of the derived class.

Public inheritance: When a public member of a base class and a member of a protected member are members of a derived class, they maintain the original access rights, and the private members of the base class are not visible in the derived class.

In public inheritance, member functions of derived classes can access public and protected members in the base class, and objects of derived classes can access only public members in the base class.

Protection inheritance: All public and protected members of a base class are protected members of derived classes and can only be accessed by its derived class member functions and not by objects of its derived classes.


2. Note:

1 The private member of the base class cannot be accessed in a derived class, and if the base class member does not want to be accessed directly outside of the class, but needs to be accessed in the derived class, it needs to be defined as protected. You can see that the protection member qualifier occurs because of inheritance.

2 public inheritance is an interface inheritance that maintains the is-a principle, and the members that are available to each parent class can also be used, because each child class object is also a parent class object.

3 "Procted/private inheritance is an implementation of inheritance, some of the base class members are not completely part of the subclass interface, is the principle of has-a relations, so in non-special cases will not use these two inheritance relationships, in most cases, the use of public inheritance.

4 "Regardless of the inheritance method, the public and protected members of the base class can be accessed inside the derived class, and the private member of the base class exists but is not visible in the subclass (not accessible)

5 "Using the class keyword is the default way of inheriting is private, the default way to inherit using a struct is public, but it is best to show the way to write the inheritance.

6 "In practical applications are generally used in the public inheritance, very few scenarios will use Protected/private inheritance.


3. Default member function for derived classes:

In an inheritance relationship, if there are no defined six member functions displayed in the derived class, the compilation system will default to the six default member functions.

The six default member functions of a class:

1 "constructor function

2 "copy constructor

3 "destructor

4 "Assignment Operation Overload

5 "Take address operator overloading

6 "Const-modified fetch address operator overload


4, the scope of the inheritance system:

1 "In the inheritance system, the base class and the derived class are two different scopes

2 The subclass and parent class have members of the same name, and child class members will mask direct access to members of the parent class (in subclass member functions, the base class can be used:: base class member access)

--Hide: Subclasses can hide inherited member variables.  For subclasses to inherit member variables from the parent class, as long as the member variables defined in the subclass and the member variables in the parent class are the same, the subclass hides the inherited member variables, that is, the subclass object and the child class itself declares that the variable that defines the method action is a member variable that is a subclass redefined. Subclasses can also hide methods that have been inherited, and subclasses hide inherited methods by overriding them.

Method overrides refer to a method defined in a subclass, and the method has the same name, return value type, and number of arguments as the parent class inherits. Subclasses can change the state and behavior of a parent class to its own state and behavior by overriding the method.

If a subclass wants to use a hidden parent method, the Super keyword must be used.

--Redefine

3 Note It is best not to define a member of the same name in the actual inheritance system.


5. Constructors for derived classes:

1 The data member of the derived class contains the data members described in the base class and the data members described in the derived class.

2 The constructor cannot be inherited, so the constructor of the derived class must initialize the data members of the base class by calling the constructor of the base class.

3 If you have child objects in a derived class, you should also include the constructor for the child object initialization.

6. Invocation order of derived class constructors:

1 constructor for base class (called in order of inheritance list)

2 constructor for an object in a derived class (called in the order of member object declarations in a derived class)

3 "derived class constructors

Attention:

1 The base class does not have a default constructor, and the derived class must display the base class name and the parameter list in the initialization list.

2 The base class does not have a constructor defined, the derived class can also use the default constructor without defining it.

3 The base class defines a constructor with a formal parameter list, and the derived class is bound to define the constructor function.

Add: The default constructor is also called the default constructor (the defaults constructor). When you declare an object, the compiler calls a constructor. If no constructor is declared in the declared class, the compiler automatically calls a default constructor, which is equivalent to a constructor that does not accept any arguments and does nothing. The compiler does not call the default constructor when there is already a declared constructor in the class.


7. Destructors for derived classes: because destructors cannot be inherited, the destructor for the base class is also called when the destructor for the derived class is executed.

The order of execution is:

1 first executes the destructor of the derived class,

2 "derived class contains destructors for member objects (call order and member objects are declared in the class in reverse order)

3 "base class destructor (the order of invocation is the reverse of the sequence declared in the derived list)


8. The function of the constructor is to initialize the object with the given value when the object is created.

Constructors without parameters are called default constructors (default constructors). There are two default constructors: one is automatically provided by the system, and the other is programmer-defined.

When you initialize a created object with a system-supplied default constructor, all data members of the Outer class object and the static class object are default values, and all data members of the automatic object are meaningless.


9, the constructor is divided into two categories: one is a constructor with parameters, can be a parameter, can be more than one parameter, the other is a default constructor, that is, a constructor without parameters.

11. Subtype: Used to describe general and special relationships between types. When there is a known type S, it behaves at least another type T, and it can also contain its own behavior, at which point the type S is a subtype of type T. The concept of subtypes involves behavior sharing, the problem of code reuse, which is closely related to inheritance. In inheritance, a child type can be implemented by public inheritance.

The importance of subtypes is to alleviate the burden of writing code and increase the rate of code reuse.

Therefore, a function can be used on objects of a certain type, and it can also be used for objects of various subtypes of that type, so that the function is not overloaded for objects that handle these subtypes.


12, type adaptation: Subtype and type adaptation are consistent, a type is a subtype of type B, then type B will be adapted to type A.


13, assignment compatibility rule: Usually in the public inheritance mode, the derived class is the subtype of the base class, then some relationship rules between the derived class object and the base class object are called assignment compatibility rules.

In the case of public succession, the compatibility rules stipulate that:

1 "Subclass object can be assigned to parent class object

2 "Parent class object cannot be assigned to a child class object

3 the pointer/reference of the parent class can point to the child class object

4 the pointer/reference to the subclass cannot point to the parent class object (can be done by forcing the type conversion)

To use the above rules, two points must be noted:

1 has the condition of the derived class's public inheritance class.

2 "The above three provisions are irreversible.

--Assignment compatibility rules:

1 Why can a derived class assign a value to a base class?

--derived class access space is greater than base class

3 "Parent pointer/reference can point to Child class object (Polymorphic implementation)


14, single inheritance, multiple inheritance, Diamond inheritance:

Single inheritance: When a subclass has only one direct parent class, it is called the inheritance relationship as a single inheritance

Multiple inheritance: When a subclass has two or more than two direct parent classes, it is called the inheritance relationship as multiple inheritance

Diamond Inheritance: The problem of ambiguity and data redundancy in diamond inheritance

Virtual inheritance solves the problem of two semantics of diamond inheritance and data redundancy.

1 "Virtual inheritance solves the problem of data redundancy and wasted space of face class objects including multi-parent objects in the diamond-like inheritance system.

2 "Virtual inheritance system looks very complex, in practice, we usually do not define such a complex inheritance system, generally not the last resort to define the architecture of diamond inheritance, the use of virtual inheritance in English to solve the problem of data redundancy also brings performance loss.


15. Under what circumstances will the compiler synthesize a default constructor? In-depth understanding of the C + + object model

--1 class has a class type member object that has its own default constructor, where the compiler also synthesizes a default constructor (not necessarily an inherited and derived relationship)

2 inheritance hierarchy, there are default constructors in the base class, and no constructors in the derived class, when the compiler synthesizes a default constructor in the derived class

3 When virtual inheritance, the default constructor is synthesized in the derived class

4 when a base class contains a pure virtual function, the default constructor is synthesized in the derived class.

--The default constructor is the compiler's default composition

--The default constructor is the one with the default value inside


16, friends and inheritance:

A friend relationship cannot inherit, which means that the base class friend cannot access the subclass private and protected members

Attention:

A friend can be a function that is called a friend function; A friend can also be a class, which is called a friend class.

In C + +, a custom function can act as a friend, and a friend is simply a custom function that accesses the private and protected members of a specified class, not a member of a specified class, and cannot be inherited naturally.

When using friends, be aware that:

1 "friend relationship cannot be inherited

2 "friend relationship is one-way, not exchange-related

3 "friend relationship does not have transitive nature

Precautions:

1 Friends can access private members of a class

2 "Friends can only appear inside the class definition, and a friend declaration may appear anywhere, usually at the beginning or end of a class definition.

3 "Friends can be ordinary non-member functions, or member functions of other classes defined earlier, or the entire class.

4 class must declare each function in an overloaded function set to be a friend.

5 The friend relationship cannot be inherited, and the friend of the base class does not have special access rights to the members of the derived class. If the base class is granted a friend relationship, only a few classes have special access rights. The derived class of the base class cannot access the class that grants the friend relationship.

17. Inheritance and static members:

The base class defines a static member, and there is only one such member in the entire inheritance system, and no matter how many subclasses are derived, there is only one static member instance


Polymorphic

1 . Type of object:

Static polymorphism: The compiler completes during compilation, and the compiler can infer which function to invoke based on the type of the function argument (which may be implicitly typed), or compile an error if there is a corresponding function to call the function.

Dynamic polymorphism: (dynamic binding) The actual type of the referenced object is judged during program execution (non-compile time), and the corresponding method is called according to its actual type.

Class Base{};class Derive:p ublic base{};int Main () {                 int A;                 Base b;                 Derive D;                 Base *PB = &B;//PB base class pointer type (static type-the type that the compiler determines during compilation); dynamic type (the type it points to)---base*                PB = &d;                System ("pause");                 return 0;} Base *pb=&b;pb=&d;

-Here the PB type has changed, that is, its dynamic type, its dynamic type is derive *


2, polymorphic: function overloading is also a polymorphic. A situation that has many forms or patterns

Polymorphism of static types: Relationships determined during compilation (early binding)

Dynamic type polymorphism: determines the actual type of the referenced object during execution, depending on its actual type, the corresponding method of invocation (late binding) (implemented through the mechanism of the virtual function)

--1 "Using virtual implementation,

2 "Invocation of a reference or pointer through a base class type: In the run process, look for pointers, define a pointer to a base class, and point to the derived class to invoke

3 "In the base class must be added Vietual, the derived class can not add;

4 The method in the base class needs to be re-implemented in the derived class.


3.

Class Base{public:                  virtual void funtest ()//virtual function                {
                   cout << "Base::funtest ()" << Endl;              }; Class Derive:p ublic base//contains funtest () in a derived class, except that the constructors and destructors in the base class are inherited {public:              virtual void funtest ()//virtual function                {                   cout << "derive::funtest ()" << Endl;              }; int main () {                 Derive D;                D.funtest ();                 Base b;                B.funtest ();                base* PB = &b;                Pb->funtest (); This is called B's funtest                PB = &d;                Pb->funtest (); The Funtest                system ("pause") of D is called here;                return 0;}

Virtual: This keyword can be polymorphic.

Note: 1 "You must add the virtual keyword before the virtual function in the base class. When you override this function in a derived class, you can add the virtual keyword without adding it.

2 when calling, use a pointer/reference to the base class to point to the object of the derived class

Dynamic binding Condition: 1 must be virtual function 2 by reference to a base class type or by a pointer call


4. The member function relationship of the same name in the inheritance system:

1 "Overload:

1 "in the same scope;

2 "function name is same, parameter is different

3 "The return value can be different

2 rewrite (overwrite):

1 is not in the same scope (base class and derived class, respectively)

2 "same function name, same parameter, same return value (Slew exception)

3 "The base class function must have the virtual keyword

4 "Access modifiers can be different

3 "redefined (hidden):

1 in different scopes (in base class and derived class, respectively)

2 "function name is the same

3 "in the base class and derived classes as long as it does not constitute a rewrite is a redefinition


5. Constructors cannot be defined as virtual

---1 constructor is used to construct the object, and virtual needs to be called through the object, but in the constructor, virtual does not have a constructor, and the object is not successfully constructed at this time.

2 "One of the first things it does when a constructor is called is to initialize its vptr. Therefore, it can only know that it is the current class, and completely ignores whether there are successors behind the object. When the compiler generates code for this constructor, it generates code for the constructor of the class-neither for the base class nor for its derived class (because the class does not know who inherits him). So the vptr that it uses must be for this class of vtable. Furthermore, the state of the vptr is determined by the constructor that was last called.

However, when this series of constructors is occurring, each constructor has been set vptr points to his own vtable. If a function call uses a virtual mechanism, it will only produce a call through his own vtable, not the last vtable (all constructors are called after the last vtable)


6, copy construction can not be defined as virtual,


7, assignment operator overloading can be defined as virtual is generally not recommended.


8, static member function, friend function can not be defined as virtual function----because they do not have the this pointer, the virtual function is the bottom is implemented with the this pointer

--the ordinary member functions of the class (including virtual functions) Add the this pointer at compile time, which can be bundled with the object, and the static function compiles without the this pointer, because the static function is common to all the class objects, so it does not add the this pointer at compile time, so it cannot be bundled with the object. The virtual function is bound with the object and the virtual function list to realize the dynamic bundle, so there is no virtual function of this pointer can be discussed.

--because a friend is not its own member function when it is declared in a class, it cannot be declared as a virtual function.

But the friend itself can be a virtual function. When this class declares her to be a friend of her own, it simply allows it to access its own private variables.


9. Pure virtual function

After the formal parameter of the member function is written = 0, the member function is a virtual function, and the class containing the virtual function is called an abstract class (also called an interface Class) an abstract class cannot instantiate an object.

If the pure virtual function is redefined in a derived class, the derived class can instantiate the object.

Class test{virtual void funtest () = 0;//no function body, just an interface that must be re-implemented in a derived class};int main () {Test t;//does not allow abstract class types             Object, the system ("pause") will be error- return 0;}               10, Virtual table class base{public:virtual void Funtest () {}//has a virtual pointer virtual void FunTest1 () {} virtual void FunTest2 () {} virtual void FunTest3 () {} virtual void FunTest4 () {}};int main ()                {Base base; Base.                Funtest (); Base.                FunTest1 (); Base.                FunTest2 (); Base.                FunTest3 (); Base.                FunTest4 ();                 System ("pause"); return 0;}                 Class drive:p ublic base{public:virtual void FunTest1 () {;                } virtual void FunTest2 () {; }};int Main () {drive d;//d contains a base, and the base inside is the same as a virtual pointer, pointing to a virtual table, notOver a function implemented in a derived class, its function address will change d.funtest ();                D.funtest1 ();                D.funtest2 ();                D.funtest3 ();                 D.funtest4 ();//A virtual function implemented in a derived class that calls the system ("pause") in the base class when it is called in a derived class and is not implemented in a derived class; return 0;}                 int main () {base base;                 drive D;                Base *pa = &base;//pa inside there will be a virtual pointer, pointing to the virtual table, and then to mobilize the virtual function pa->funtest ();                Pa->funtest1 ();                Pa->funtest2 ();                Pa->funtest3 ();                Pa->funtest4 ();                PA = (base*) &d;//d There will be a base,base inside will contain a virtual pointer to another virtual table;; The type conversion here does not work, and does not point to the previous virtual table pa->funtest ();                Pa->funtest1 ();                Pa->funtest2 ();                Pa->funtest3 ();                Pa->funtest4 ();                 System ("pause"); return 0;}


Inheritance and polymorphism in C + + (UP)

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.