C ++: class inheritance

Source: Internet
Author: User
Tags class operator types of functions

1.Base class and derived class:

When a class is derived from another class, the original class is called the base class, And the inherited class is called the derived class. The basic syntax is: Class subclassname: Public baseclassname {}; Public indicates public derivation. Of course, private and protected are also supported ). A derived class object contains a base class object. When using public derivation, the Public Member of the base class will become the Public Member of the derived class, and the private part of the base class will also be called a part of the derived class, but it can only be accessed through the public and protected methods of the base class.

A derived class cannot directly access a private member of the base class, but must be accessed through the class method of the base class.

Derived class constructor:

(1) The base class object is first created

(2) The derived class constructor should pass the base class information to the base class constructor through the member initialization list: for example:

Rateplayer: rateplayer (int r, cosnt char * fN, const char * ln): tabletennisplayer (FN, LN)

{

Rating = R;

}

The base class object must be created first. If the base class constructor is not calledProgramUse the default base class constructor. In general, unless the default constructor is used, the base class constructor should be called explicitly.

(3) The derived class should initialize the new data member of the derived class

Note: When creating a derived class object, the program first calls the base class constructor, and then calls the derived class constructor. The base class constructor replicates the data members inherited from the initialization. The derived class constructor is mainly used to initialize new data members. A derived class constructor always calls a base class constructor. When a derived class Object expires, the program first calls the derived class destructor and then calls the base class destructor.

2.A special relationship between a derived class and a base class

There are some subtle relationships between the derived classes and the base classes, mainly including:

(1) The derived class object can use the method of the base class, but the method is not private

(2) The base class pointer can point to a derived class object without converting the display type; the reference is also, the base class reference can reference the derived class object without converting the display type; however, base class pointers and references can only be used to call base class methods, but cannot call methods of derived classes (without considering virtual functions)

(3) The base class object and address cannot be assigned to the reference and pointer of the derived class.

(4) Reference compatibility. You can also initialize a base class object to a derived class object.

(5) You can also assign a derived class object to a base class object.

3.Inheritance---- Is-Link

Although in C ++, you can use public inheritance to create has-a, is-imlimented-as-A or uses-a relational models, but to avoid programming problems, we recommend that you stick to the is-a relationship.

4.Multi-state public inheritance

When the behavior of a method in the base class is different from that in the derived class, modify the method in the base class to make it polymorphism. There are generally two mechanisms for implementing multi-state public inheritance:

(1) Redefine the method of the base class in the derived class

(2) Use virtual functions (Virtual Methods)

The first one is not mentioned. Let's talk about the second one. virtual functions and keywords are virtual. Virtual keywords are required in the declaration and are not used in definition implementation.

Why do we need to use virtual functions?

If the method is called by reference or pointer instead of object, if the virtual function method is not used, the program selects a method based on the reference type or pointer type. If the virtual function is used, the program selects a method based on the type of the object to which the reference or Pointer Points.

For example, there is a brass class. subbrass is a derived class of brass, and there is a show () method,

Brass Tom;

Subbrass Jack;

Brass & pt1 = Tom;

Brass & pt2 = Jack;

Pt1.show ();

Pt2.show ();

If show () is not a virtual function, the last two rows above are

Pt1.show (); // call Brass: Show ();

Pt2.show (); // call Brass: Show ();

If show () is a virtual function, the last two rows above are

Pt1.show (); // call Brass: Show ();

Pt2.show (); // call subbrass: Show ();

Virtual destructor: to ensure that the washed function is called in the correct order when the object is released.

Note: If you re-define a base class method in a derived class, you should declare the base class method as your method. In this way, the program selects a method based on the object to which the reference or Pointer Points. Declaring a virtual destructor for the base class is also a convention.

Static and Dynamic Association:

Joint Editing:Source codeFunction call is interpreted as executing a specific functionCodeFunction Name Association. In the compilation process, C/C ++ is called static Association and early Association. During the program running, the Association is called Dynamic Association and later Association. The compiler uses static Association for non-Virtual Methods and Dynamic Association for virtual methods.

Note: If you want to redefine the method of the base class in the derived class, set it to a virtual method; otherwise, set it to a non-virtual method.

Working Mechanism of virtual functions:

C ++ specifies the behavior of virtual functions, but leaves the implementation method to the compiler author. You can use virtual functions without knowing the implementation method. However, understanding the operating principles of virtual functions helps you better understand the virtual functions:

Generally, the compiler processes virtual functions by adding a hidden member to each class object. The hidden member saves a pointer to the function address array. This array is called a virtual function table (vtbl ). The virtual function table stores the addresses of virtual functions declared for class objects. For example, a base class object contains a pointer pointing to the address table of all virtual functions in the base class. Derived class

It will contain a pointer pointing to the opposite address table. If the derived class provides a new definition of the virtual function, the virtual function table will save the address of the new function. If the derived class does not redefine the virtual function, the vtbl will save

The address of the original function version. If the derived class defines a new virtual function, the address of the function will also be added to vtbl. Note that no matter how many virtual functions are contained in the class, you only need to add one address Member table to the object, but the table size is different.

Precautions for virtual functions:

(1) using the keyword virtual in the declaration of the base class method enables the method to be virtual in the base class and all the derived classes (including derived classes from the derived class, because after a method is declared as virtual in the base class, it automatically defaults to virtual in the derived class.

(2) If you use a reference to an object or a pointer to call a virtual method, the program uses a method defined for the object type instead of a method defined for the reference or pointer type. This is the dynamic Association (later) Association. This behavior is very important, because it enables the base class pointer or reference to point to the derived class object.

(3) If the defined class is used as the base class, declare the methods to be redefined in the derived class as virtual methods.

(4) The constructor cannot be a virtual function. Because the derived class cannot inherit the constructor, it makes no sense.

(5) fictitious functions should be virtual functions, unless the class does not have a base class. Generally, a virtual destructor should be provided to the base class, even if it does not need a destructor.

(6) You can't use a virtual function because you are not a class member and only a class member can be a virtual function. If the design problem is caused by this reason, you can use the virtual function to solve the problem.

(7) If the derived class does not redefine the function, the base class version of the function is used. If the derived class is located in the derived class chain, the latest virtual function method will be used, unless the base class is hidden.

(8) redefinition of the hidden method:

Class baseclass

{

Public:

Virtual void show (int A) const;

...

}

Class subclass: Public baseclass

{

Public:

Virtual void show () const;

...

}

The following code is available:

Subclass SC;

SC. Show (); // This is valid and the subclass method is called.

SC. Show (5); // This is invalid because the show () method of the base class bassclass has been hidden in the methods in the subclass class.

There are two empirical rules:

First, if the inherited method is redefined, it should be completely consistent with the original prototype. However, if the returned type is a base class reference or pointer, it can be changed to a reference or pointer pointing to a derived class. This feature is called

Covariance of return type, because the return type varies with the class type:

Lass baseclass

{

Public:

Virtual baseclass & show (int A) const;

...

}

Class subclass: Public baseclass

{

Public:

Virtual subclass & show () const;

...

}

Second, if the base class declaration is overloaded, all base class versions should be redefined in the derived class.

Class baseclass

{

Public:

Virtual void show (int A) const;

Virtual void show (Double X) const;

Virtual void show () const;

...

}

Class subclass: Public baseclass

{

Public:

Virtual void show (int A) const;

Virtual void show (Double X) const;

Virtual void show () const;

...

}

This is because if only one version is redefined, the other two versions will be hidden and the derived class objects will not be able to use them. In addition, if no modification is required, the new definition can only call the base class version.

5. ProtectedAccess control:

Similar to private, protected can only access class members in the protected section with public class members outside the class. The difference between protected and private is only reflected in the derived class. The members of the derived class can directly access the protected members of the base class, but cannot access the Private Members of the base class. Therefore, for external, the behavior of protecting members is similar to that of private members. For a derived class, the behavior of protecting members is similar to that of public members.

Warning it is best to use private access control for the class member data. Do not use protected access control. At the same time, use the base class method to allow the derived class to access the base class data. However, it is useful for member functions to protect access control. It allows Derived classes to access internal functions that are not available to the public.

6.Single Design Mode:

If you want to have only one real column of the class returned to the calling program, you can use the Singleton pattern ):

Class theonlyinstance

{

Public:

Static theonlyinstance * gettheonlyinstance (); // The Factory method used to obtain the instance.

Protected:

Theonlyinstance (){}

};

Declare the constructor as protected and remove the public constructor. Prevents local instances from being created.

Theonlyinstance the; // not allowed

You can only use the public static method gettheonlyinstance to restore the class.

Declare the constructor as protected and remove the public constructor. Prevents local instances from being created.

Theonlyinstance * theonlyinstance: gettheonlyinstance ()

{

Static theonlyinstance OBJ;

Return & OBJ;

}

To retrieve the pointer to this class, you only need to call gettheonlyinstance ()

Theonlyinstance * ptheonlyinstance = theonlyinstance: gettheonlyinstance ();

Single Design Mode C ++ code implementation:

# Include <iostream>

Using namespace STD;

// C ++ implementation of the Singleton class

Class Singleton

{

PRIVATE:

Singleton (); // note: the constructor method is private.

Virtual ~ Singleton ();

Static Singleton * instance; // unique instance

Int var; // member variable (for testing)

Public:

Static Singleton * getinstance (); // factory method (used to obtain an instance)

Int getvar (); // obtain the value of VaR

Void setvar (INT); // sets the value of var.

};

// Constructor implementation

Singleton: Singleton ()

{

This-> Var = 20;

Cout <"Singleton constructor" <Endl;

}

Singleton ::~ Singleton ()

{

Delete instance;

}

// Initialize static members

Singleton * singleton: instance = new Singleton ();

Singleton * singleton: getinstance ()

{

Return instance;

}

// Seter & getter Function

Int singleton: getvar ()

{

Return this-> var;

}

Void singleton: setvar (INT var)

{

This-> Var = var;

}

// Main

Int main (INT argc, char * argv [])

{

Singleton * ton1 = singleton: getinstance ();

Singleton * ton2 = singleton: getinstance ();

Cout <"ton1 Var =" <ton1-> getvar () <Endl;

Ton1-> setvar (150 );

Cout <"ton2 Var =" <ton2-> getvar () <Endl;

Return 0;

}

The output is as follows:

Singleton Constructor

Ton1 Var = 20

Ton2 Var = 150

In the output result, the constructor is called only once. ton1 and ton2 point to the same object.

7.Abstract base classes and pure virtual functions:

★Abstract class: A class can abstract different objects to express an abstract concept and a common interface. This class cannot instantiate (create) objects.

★Pure virtual function (pure virtual): it cannot be implemented (description function) in this class, and must be implemented in the subclass.

Example:

Virtual typet function_name (parameter_list) = 0;

 

Virtual void draw () = 0; // painting, pure virtual function;

Virtual void rotate (double) = 0; // rotate, pure virtual function;

★Abstract class: If a class contains pure virtual functions, this class is called an abstract class.

★An abstract class can only be used as a base class, cannot be used as a derivation, and cannot be instantiated (created) objects. If a class contains at least one pure virtual function, the class is an abstract class. A subclass of an abstract class can add more data members and member functions.

★The subclass of an abstract class can be an abstract class. You can add more member functions and member methods until an object can be generated.

★Abstract classes cannot construct objects, so their constructors cannot be called independently. Its constructor can only be called in the member initialization list of the subclass.

★Abstract classes do not necessarily have destructor. If they exist, they must be virtual destructor.

★★★A function cannot have a value parameter of an abstract class Object <a value cannot be passed through a parameter>. This function cannot return a value of an abstract class object. However, pointers and references of the abstract class can be used as parameters, and pointers and references of the same abstract class can be used as return value types of functions. Because they can point to or reference subclass objects of abstract classes.

Abstract base class interface rules: abstract base class requires that a specific derived class overwrite its pure virtual function, forcing the derived class to follow the rules set by the abstract base class.

8.Inheritance and dynamic memory allocation:

(1) do not use new for Derivation

Call the constructor to process the new derived members, and then call the constructor of the base class. (Usually, you need to define the Destructor as virtual in the base class, because

When a base class reference or pointer is called, The Destructor can only process the base class object, and the derived class cannot be processed. Therefore, after being defined as virtual, the security requirements will be met.

Order, correct processing)

If the new type is not used in the derived class, the default destructor and the default complex constructor are used in the derived class. The default value assignment function meets the requirements, that is, no need to define the display destructor, copy constructors and value assignment operators

(2) use the new

If a derived class uses new, the displayed destructor must be defined for the derived class, And the constructor and value assignment operators must be copied.

Friend functions of a derived class: You usually need to nest the corresponding friend functions of the base class to complete operations on the base class members.

9.Static member inheritance:

Static members can also be defined in a class, but static members are public to all objects. Static members are divided into static data members and static member functions.

1. static data member

To define a static data member in a class, add the keyword "static" before the member.

The statement format for defining static data members is as follows:

Class Name

{

......

Member name of the static type specifier;

......

};

Static data members are shared by all objects in the class. The space occupied by static data members is not allocated with the generation of objects, nor is it recycled with the disappearance of objects. The operations on static data members are different from the operations on general data members in the class. static data members defined as private members cannot be accessed by the outside world. Static data members can be accessed by functions with any access permission.

Static data members share all objects of the class, but do not belong to any specific object. Therefore, static data members of the class must be initialized, however, its initialization cannot be performed in the class constructor. Its initialization statement should be written in the global area of the program, and its data type and class name must be specified, the initialization format is as follows:

Type Class Name: variable name = value;

Static data members described in the public part of the class can be directly accessed outside the class without using member functions. However, the class name must be used to specify the class to which the member functions belong, the ACCESS format is:

Class Name: static data member name

Static data members described in the non-public part of the class can only be accessed by member functions of the class. The access method is the same as that of common data members in the category class, but cannot be accessed outside the class.

2. static member functions

The definition of a static member function is the same as that of a common member function, but the static keyword is prefixed. The definition format is as follows:

Class Name

{

...

Static function name (parameter)

{Function body}

...

};

Note:

(1) A Class static member function can only be a member of the class static data, but not a member of a common function in the class (non-static data member ), because normal data members make sense only when class objects exist.

(2) static member functions are associated with the class instead of the class objects. Therefore, public static member functions in the class are called externally, you must add "Class Name:" To the left of the class, instead of calling the public static member function through the object name. Private Static member functions in the class cannot be called outside the class.

10.Class summary:

I learned it now and have a deep understanding of class inheritance. So far I will make a summary.

(1) What does the derived class inherit from the base class? What can't be inherited from the base class?

The Public Member of the base class becomes the Public Member of the derived class. The protected member of the base class becomes the protected member of the derived class. The private member of the base class is inherited but cannot be accessed directly. Constructor, destructor, value assignment operator, and youyuan cannot be inherited.

(2) constructor:

Unlike other functions, constructor creates an object, either with no parameters or with default values for all parameters.

(3) destructor:

You must define the display destructor to release all the memory that the class constructor uses to run with new, and complete any special cleaning work required for class objects. For a base class, a virtual destructor should be provided even if it does not need constructor.

(4) assignment operator:

It cannot be inherited. If the class constructor uses new to initialize the pointer, a display value assignment operator must be provided, because for the base class part of the derived object, c ++ uses the base class operator, so you do not need to redefine the value assignment operator for the derived class unless it adds data members that require special attention. However, if a derived class uses new, the displayed value assignment operator must be provided. Each member of the class must be assigned a value assignment operator, not just new members.

How can I assign a derived class object to a base class object? The answer is yes, but only the members of the base class are involved. In turn, how does one assign a base class object to a derived class object? The answer is perhaps. If a derived class contains such a constructor, that is, to convert a base class object to a derived class object, you can assign the base class object to the derived class object. If a derived class defines a value assignment operator used to assign a base class object to a derived class object, you can also do so. If none of the above conditions is met, the base class object cannot be assigned to the derived class object unless the display type conversion is forced.

(5) youyuan:

Because you are a non-class member, you cannot inherit. However, if you want the derived class's friend functions to be able to use the base class's friend functions, you can do this by forcing type conversion to reference the derived class, sit or station conversion to base class references or pointers, then, the converted pointer or reference is used to call the membership function of the base class:

Ostream & operator <(ostream & OS, const subclassname & SC)

{

OS <(const baseclassname &) SC; // converts the reference of the derived class to the reference of the base class.

...

Return OS;

}

Of course, you can also use the operator dynamic_cast <> to force type conversion.

(6) Virtual Methods:

When designing a base class, pay attention to whether to declare the class method as virtual. If you want the derived class to be able to redefine the method, you should declare the method as virtual in the base class. If you do not want it, you do not have.

(7) instructions on using basic methods:

 ● The object of the derived class automatically uses the base class method inherited by the class. If the derived class is not redefined

● The constructor of the derived class automatically calls the base class function.

● The constructor of a derived class automatically calls the default constructor of the base class. If other constructor is not specified in the member initialization list.

● The derived class constructor displays and calls the base class constructor specified in the member initialization list.

● The derived class method can use the scope resolution operator to call public and protected basic class methods.

● You can use forced type conversion to convert a derived class to a base class reference or pointer, and then use the converted pointer or reference to call the base class membership function.

(8) Summary table of class member function attributes:

Member Function Attributes

 

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.