"Reprint" The base class and derived class in C + +

Source: Internet
Author: User







Transferred from: http://www.cnblogs.com/sujz/articles/2044365.html


The inheritance of derived classes is summarized as follows:


How to Inherit Description
Public The public and protected members of the base class are inherited by the derived class, preserving the original state
Private Public and protected members of the base class are inherited by derived classes and become private members of derived classes
Protected

The members of the base class public and protected are inherited by the derived class and become protected members of the derived class




Note: A private member of a base class cannot be accessed by a derived class, regardless of the inheritance method. As can be seen from the table above, methods and properties declared as public can be accessed arbitrarily, and methods and properties declared as protected are accessible only to the class itself and its subclasses, whereas methods and properties declared as private can only be accessed by objects of the current class.  


1. The friend function must be declared in the class and defined outside the class, and the declaration must precede the function return type with the keyword friend. A friend function is not a member function of a class, but it can access private and protected type data members in a class.   



2. When a virtual function is redefined, the number and type of arguments must exactly match the virtual functions in the base class, which is completely different from the function overloads.   



3. #include < filename > and # include "File name"


    • In the two formats that the file contains, the first format is used to contain the header files that are provided by the system and placed in the specified subdirectories, while the second format is used to contain the header files or other source files that are placed in the current directory or other directory, as defined by the user.   


4. An array can also be used as an argument and a parameter for a function, and if the array element is an argument to a function, its usage is the same as the variable. When the array name is used as the argument and formal parameter of a function, the address of the array is passed. When passing by value, the value of the transfer is one-way, that is, you can only pass parameters to the parameter, and cannot pass the argument back from the parameter. The initial value of the formal parameter is the same as the argument, and when the value of the formal parameter changes, the argument does not change, and the final values are different. When the array name is passed as a function parameter, the real parameter group changes when the parameter group changes, because the actual arguments and formal parameters are the same array.   



Note: The real parameter group and the shape parameter group type should be consistent, if inconsistent, the result will be wrong; The shape parameter group can also not specify the size, the array name is followed by an empty square bracket when the array is defined, in order to handle the array elements in the called function, you can set another parameter, passing the number of array elements. such as: int sum (int array[],int n);   



5. What are the differences between overloading, overwriting and hiding?   



Overloading of functions means that C + + allows multiple functions with the same name to exist, but the parameters of each function with the same name must differ: the number of formal parameters is different, or the number of formal parameters is the same, but the parameter types are different.  



Override refers to the existence of a redefined function in a derived class whose function name, parameter column, and return value type must be strictly consistent with the corresponding function in the half-class, where the covering function and the overridden function are the same as the body of the function (the part of the curly braces). The overridden version of a subclass is automatically called when a derived class object invokes the same name function in the subclass, rather than the overridden version of the function in the parent class, which is called overwrite.



Here we tell the difference between overloading and overwriting from the angle of the member function.



The member functions are overloaded with the following characteristics: 1) the same range (in the same Class), 2) The function name is the same, 3) the parameters are different; 4) The virtual keyword is optional.



The features covered are: 1) different ranges (in both derived and base classes), 2) functions with the same name, 3) the same parameters, 4) The base class function must have the virtual keyword.


For example, in the following program:

#include <iostream.h>
Class Base
{
Public
void f (int x) {cout << base::f (int) << x << Endl;}
void f (float x) {cout << base::f (float) << x << Endl;}
virtual void g (void) {cout << "base::g (void)" << Endl;}
};

Class Derived:public Base
{
Public
virtual void g (void) {cout << "derived::g (void)" << Endl;}
};

void Main (void)
{
Derived D;
Base *PB = &d;
Pb->f (42); Run Result: base::f (int) 42
Pb->f (3.14f); Operation Result: Base::f (float) 3.14
Pb->g (); Run Result: derived::g (void)
}





The function base::f (int) is overloaded with base::f (float), and base::g (void) is overridden by derived::g (void).



Hiding refers to a function of a derived class that masks a base class function with the same name as the following: 1) If the function of the derived class has the same name as the function of the base class, the parameters are different. At this point, the function of the base class is hidden, regardless of the virtual keyword (Note that it is not 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).



For example, in the following program:





#include <iostream.h>

Class Base
{
Public
virtual void F (float x) {cout << base::f (float) << x << Endl;}
void g (float x) {cout << base::g (float) << x << Endl;}
void h (float x) {cout << base::h (float) << x << Endl;}
};

Class Derived:public Base
{
Public
virtual void F (float x) {cout << derived::f (float) << x << Endl;} After being inherited, virtual is optional, but preferably there. After inheritance, it is still a virtual function.
void g (int x) {cout << "derived::g (int)" << x << Endl;}
void h (float x) {cout << derived::h (float) << x << Endl;}
Using base::g;//This sentence is used to refer to the hidden part of the parent class.
};





Through analysis, you can get:



1) The function derived::f (float) is covered with base::f (float).



2) function derived::g (int) hides the base::g (float), note that it is not overloaded.



3) The function derived::h (float) hides the base::h (float) instead of overwriting it.



After reading the previous example, we may not understand what is the difference between hiding and covering, because we are talking about the surface phenomenon, how to achieve the situation. Below we will analyze what is the difference between covering and hiding in the application. In the following program, BP and DP point to the same address, it should be said that the results should be the same, but it is not true.





void Main (void)
{
Derived D;
Base *PB = &d;
Derived *PD = &d;
Good:behavior depends solely on type of the object
Pb->f (3.14f); Operation Result: Derived::f (float) 3.14
Pd->f (3.14f); Operation Result: Derived::f (float) 3.14
Bad:behavior depends on type of the pointer
Pb->g (3.14f); Operation Result: Base::g (float) 3.14
Pd->g (3.14f); Run Result: derived::g (int) 3
Bad:behavior depends on type of the pointer
Pb->h (3.14f); Operation Result: Base::h (float) 3.14
Pd->h (3.14f); Operation Result: Derived::h (float) 3.14
}





Please note that the F () function is covered, while g () and H () are hidden. From the running results above, we can notice that when the function f () is called with the base class pointer and the derived class pointer in the overlay, the system executes the derived class function f (), not the base class F (), which is actually the "interface" function that is completed. In the hidden mode, when the function f () is called with a base class pointer and a derived class pointer, the system differentiates between the base class pointer invocation, the system executes F () of the base class, and when the derived class pointer is called, the system "hides" the base class F () and executes the derived class F (), which is the origin of "



Overloading (Overload): This is a good understanding, in the same space domain with the same name. Parameters must be different, not about virtual.



Overwrite (override): same name, same parameter, with virtual, covering good understanding such as show () function, a derives B, if Show () in B overrides show () in a, but there are still two show () in B, regardless of the class A pointer, Class B object invocation , you can only invoke the Class B own show (), and the show () function inherited from Class A is actually overwritten. The answer is not right. At this point, the Class B object can be displayed in the call Category A inherited from show ();



Program code:





#include <iostream>
using namespace Std;

Class A
{
Public
virtual void Show ()
{
cout << a << Endl;
}

int A;
};

Class B:public A
{
Public
void Show ()
{
A::show ();
Explicitly call the "show () function inherited by Class A" in your own class, like this, when you explicitly indicate a function of a class, the compiler handles this way: first in your own class there is no A::show (), if found, called. Do not continue to find in Class A, if not found, The function is called in the explicitly indicated class (that is, Class A). A::show () can be found in Class B, of course, as it is indicated in the base class that this function is a virtual function.
}
int b;
};

int main ()
{
A;
A.A = 3;
A.show ();

b b;
B.B = 4;
B.show ();
B.a::show (); Show "show () function inherited by Class A" in the call itself class

return 0;
}





Summarize:



The popular class B still has two show (), Just call Show () inherited by a () can only be called by the explicit method [class name:: Virtual function name], regardless of the base class A pointer (b b; A *p = &b; P->show ()) or the object of a derived class (b b; b.show ()), can only invoke the show () function of Class B's own existence



Hiding Hide:



1: same name with same parameter without virtual



2: Different parameters with the same name regardless of whether or not virtual



Program code:





Class A
{
Public
void Show () {}; Ref. 1
void Rose (int a) {}//No. 2
};

Class B:public A
{
Public
void Show () {}; Ref. 3
void Rose (int a, int b) {}; Ref. 4
};





Show () and Rose () in class B are clearly hidden from the show () and Rose () hidden understandings of Class A: there are actually two show (), two Rose () in class B; But why not call overloading? You would think so, but I can tell you that, because two show (), two Rose () in class B, not all can be called by Class B objects.



Number 1 and number 2, even if it exists in class B, but can only be called through a pointer to Class A, and cannot be called through Class B objects, such as:



Program code:





A *p = new B;
P->show ();
P->rose (3);
P->rose (3,5); Error





Numbers 3 and 4, can only be called through Class B objects, not through pointer to class A, such as:



Program code:





b b;
B.show ();
B.rose (3,5);
B.rose (4); Error





6. Use parameter lists to differentiate overloaded functions, why return values cannot differentiate between overloaded functions?



For example, there are two functions: int fun (); Double Fun (); If you write Fun (), then the compiler doesn't know who to call. The return value cannot be determined until the function call is complete, but the program needs to know exactly which overloaded function to invoke when calling the function.



7. Relationship between a derived class and a base class


    • A derived class object can use a method of the base class, provided that the method is not declared private in the base class. A base-class pointer can point to a derived class object without an explicit type conversion, and a base class reference can reference a derived class object without an explicit type conversion. However, a base class pointer or reference can only be used to call a base class method and cannot invoke a method of a derived class. Typically C + + requires reference and pointer types to match the assigned type, but this rule is an exception to inheritance. This exception is only one-way, however, and it is not possible to assign base class objects and addresses to derived class references and pointers.


8. Static and dynamic linking



Which executable code block will be used when the program calls the function? The compiler is responsible for answering this question. The function calls in the source code are interpreted as executing a specific function code block called a function name union. In the C language, this is very simple, because each function name corresponds to a different function. In C + +, this task is more complex due to function overloading. The compiler must look at the function arguments and function names to determine which function to use. However, this type of compilation can be done in the compile process. A binder is called a static binder/binding during compilation, also known as an early binder/binding. However, virtual functions make this work more difficult. Because the function that is used cannot be determined at compile time, because the compiler does not know what type of object the user will choose. Therefore, the compiler must generate code that can select the correct virtual method when the program runs, which is known as Dynamic Union/binding, also known as late-linking/binding.






"Reprint" The base class and derived class in C + +


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.