C + + Programming thought---14th Chapter inheritance and combination

Source: Internet
Author: User

1, two ways of implementing code reuse

Combination: I simply create an object of an existing class in the new class. Because the new class is composed of objects that already exist in the class, they are called combinations. This allows the functionality of existing classes to be added to the new class.

Inheritance: extends the parent class.

2, the private member of the base class can only be accessed through the interface provided by the base class.

3, the function that calls the base class, hidden or overwritten can be accessed through the scope operator.

4, overload

(1) Same range (in the same class)

(2) The function has the same name

(3) different parameters

(4) virtual keyword is optional

Overwrite (derived class function overrides base class function)

(1) different ranges (in the derived and base classes, respectively)

(2) The function has the same name

(3) Same parameters

(4) The base class function must have a virtual keyword

Hide (a function of a derived class masks a base class function with its namesake) as long as the subclass defines a function with the same name as the base class (regardless of the return value, the argument list is the same), the base class version is hidden as long as the names are the same.

(1) If the function of the derived class has the same name as the function of the base class, but the parameters are different. At this point, the function of the base class is hidden, regardless of the virtual keyword (note not to be confused with overloading)

(2) If the function of the derived class has the same name as the function of the base class, and the parameters are the same, the base class function does not have the virtual keyword. At this point, the function of the base class is hidden (be careful not to confuse the overlay)

5, initialize the role of the list: There are two ways to initialize a member of a class, one is to use the initialization list, and the other is to assign a value in the constructor body. The use of initialization lists is primarily based on performance issues, and for built-in types such as int, float, and so on, using the Initialize class table and initializing in the constructor body is not very different, but for class types it is best to use the initialization list, why? The process of invoking the default constructor one less time with the initialization list is very efficient for data-intensive classes. When an initialization list is not used, the compiler invokes the default constructor and then invokes the assigned function to copy the class if it has a member variable, and the member variable is of class type. Impact efficiency.

6, in addition to performance issues, some of the time when the initialization of the list is indispensable, the following situations must use the initialization list:

(1) Constant members, because constants can only be initialized and cannot be assigned, so they must be placed in the initialization list

(2) Reference type, the reference must be initialized at the time of definition, and cannot be re-assigned, so it is also written in the initialization list

(3) A class type that does not have a default constructor, because using an initialization list does not have to call the default constructor to initialize, but instead calls the copy constructor initialization directly.

A hardening mechanism for 7,c++ is that there is no way to enter the constructor of a class, member object (class, built-in type), in order to prevent the function of the parent class from calling the function within the member object in the constructor. Call the constructor of the base class first, then call the constructor of the member object, and then go to your own constructor.

8, pseudo-constructor syntax int i (100);

9, the order in which the constructors are called is constructed from the root down, and the destructor is called in reverse direction from the bottom to the root. The direction of construction and destruction is exactly the opposite. The order in which multiple class member variables are constructed is not in the order in which they were initialized, but in terms of the location declared in the class.

10, the compiler automatically generates a

(1) The default constructor. As long as you define a constructor (no matter what constructor), the compiler does not generate it automatically.

(2) Copy constructor.

(3) Assignment operator =.

(4) destructor

11, the function that cannot be inherited has

(1) Constructor function. Because it works against its own layer.

(2) destructor. Because its role is also aimed at their own layer.

(3) "=", the assignment operator, the subclass has a default assignment operator, and then the assignment operator of the parent class is hidden.

12, the common denominator of static member functions and non-static member functions

(1) They can all be inherited.

(2) If we define a static member function, the function with the same name in its base class is also hidden.

13, a static member function cannot be a virtual function. Because he doesn't have this pointer.

14, combination: In order to produce a new function, the car is an example of a car that has a lot of components. The relationship of Has-a

15, inheritance: Use the old interface to define new features. Is-a's relationship. When deciding when to use a combination or a construct, there is also a point of judgment, considering whether an upward type conversion is required.

16, three types of inherited permissions:

Public inheritance

Protect inheritance

Private inheritance

Combination Result:

In the inheritance mode subclass of the base class

Public and public inheritance = Public
Public & protected Inheritance and protected
Public & private inheritance = Private

Protected & Public succession = Protected
Protected & protected Succession = Protected
Protected & Private succession = Private

Private & Public Inheritance--Subclass No access
Private & protected inheritance = Subclass No access
Private & Private Inheritance--subclass No access

The result of these combinations shows that the members under these permissions are in the subclass, but the members of the subclasses are determined by the inheritance method.

(1), public inheritance does not change access rights of base class members
(2), private inheritance makes the access rights of all members of a base class in a subclass private
(3), protected inheritance changes the public member in the base class to the protected member of the subclass, and the access rights of the other members are not changed.
(4), the private member in the base class is not affected by the way of inheritance, the subclass never has access.

17, we summarize the C + + class Three ways of controlling permissions as follows:

Public
access Rights protected Private
For this class Visible Visible Visible
Sub-class Visible Visible Not visible
to external (caller) Visible Not visible Not visible

18, private inheritance, when connected to runtime type recognition, is particularly complex and should be noted. (learned in later chapters)

19, private inherited members are public (only the member functions of the base class are publicly, protected permissions, private is not allowed, experiment over)

Class Car
{
Public:
    Car () {}
    void Hello ()
    {
        Qdebug () << "Hello!";
    }
Protected
    void haha ()
    {
        Qdebug () << "haha!";
    }
};
Class Bmw:private Car
{
Public:
    Using Car::hello;
    Using Car::haha;
};
int main (int argc, char *argv[])
{
    Qcoreapplication A (argc, argv);
    Car car;
    BMW BMW;
    Bmw.hello ();
    Bmw.haha ();
    return A.exec ();
}

20, multiple inheritance disputes (follow-up learning).

21, up type conversion: Subclass to Parent class is safe. The up-type conversion loses the member variables unique to the subclass (in addition to the virtual functions overridden by subclasses).

Child child;

Parent * Parent = &child;

At this point, the parent can only manipulate portions of the child that are part of the base class (except for overridden virtual functions).

22, another similar problem that often occurs with inheritance is when you implement a copy constructor for a derived class. Take a look at the following constructor, whose code is similar to the one just discussed above:

Class Base
{
Public
  Base (int initialvalue = 0): X (InitialValue)
  {
      Qdebug () << "I am base constructor!";
  }
  Base (const base& RHS): X (rhs.x)
  {
      Qdebug () << "I am base copy-constructor!";
  }
Private
  int x;
};
Class Derived:public Base
{
Public
  Derived (int initialvalue = 1): Base (InitialValue), Y (InitialValue)
  {
      Qdebug () << "I am derived constructor!";
  }
  Derived (const derived& RHS): Y (RHS.Y)
  {
      Qdebug () << "I am derived copy-constructor!";
  }                    //Bad copy constructor, the copy constructor that calls the parent class needs to be displayed in the initialization list. The default constructor for the base class is called, as long as it is not the constructor that we are calling, which is the default constructor.
If this copy constructor of a subclass is dropped, the compiler automatically generates a copy constructor that invokes the copy constructor of the base class.
Private
  int y;
};
int main (int argc, char *argv[])
{
    Qcoreapplication A (argc, argv);
    Derived child1;
    Derived child2 = child1;
    return A.exec ();
}

The result of the copy constructor for the subclass is not dropped:
I am base constructor!
I am derived constructor!
I am base constructor!
I am derived copy-constructor!
The result after the injection is:
I am base constructor!
I am derived constructor!
I am base copy-constructor!
As you can see, the copy constructor that is generated by default is a constructor that can call a copy of the base class, and if you declare a copy constructor, you must display the copy constructor of the base class in the initialization list, otherwise the default constructor is called.


Class derived presents a bug that occurs in all C + + environments: When a copy of derived is created, its base class part is not copied. Of course, the base part of the derived object was created, but it was created with the default constructor of base, and member X was initialized to 0 (default parameter value of the default constructor) without regard to the X value of the object being copied!

To avoid this problem, the copy constructor of the derived must ensure that the copy constructor of the base is called instead of the default constructor of base. This is easy to do, as long as you specify an initialization value for base in the member initialization list of the copy constructor of derived:

Class Derived:public Base {
Public
  Derived (const derived& RHS): Base (RHS), Y (rhs.y) {}
  ...
};

Now, when a derived object is copied with an existing object of the same type, its base part is also copied.

If a subclass does not implement a copy constructor, the compiler automatically generates a copy constructor that automatically calls the copy function of the base class and then the copy constructor of the member object (or performs a bit copy on the built-in type).

Conclusion: It is important to remember that whenever we create our own copy constructors, we call the copy constructors of the base class correctly (as the compiler does).

C + + Programming thought---14th Chapter inheritance and combination

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.