C + + abstract class

Source: Internet
Author: User
Tags abstract definition function prototype

Definition of a pure virtual function
A pure virtual function is a virtual function declared in a base class that is not defined in the base class, but requires that any derived class define its own implementation method. The method of implementing a pure virtual function in a base class is to add "= 0" after the function prototype

Second, the reasons for the introduction:
1, in order to facilitate the use of polymorphic features, we often need to define virtual functions in the base class.
2, in many cases, the base class itself is unreasonable to generate objects. For example, animals as a base class can be derived from tigers, peacocks and other sub-categories, but the animals themselves generated objects are obviously unreasonable.
In order to solve the above problems, the concept of pure virtual function is introduced, the function is defined as pure virtual function (method: Virtual ReturnType functions () = 0;), the compiler requirements must be overloaded in derived classes to achieve polymorphism. A class that contains a purely virtual function is called an abstract class, and it cannot produce an object. This is a good solution to both of these problems.

Classes with pure virtual functions are called abstract classes. An abstract class is a special class that is built for abstraction and design purposes, and it is in the upper layer of the hierarchy of inheritance. Abstract Classes cannot define objects, and in practice, in order to emphasize that a class is an abstract class, the constructor of the class can be described as a protected access control permission.

The primary function of an abstract class is to associate the organization in an inheritance hierarchy by providing it with a common root, derived from the root of the dependent subclass.

Abstract classes describe the general semantics of the operation interfaces of a set of subclasses, which are also passed to subclasses. In general, abstract classes describe only the common operating interfaces of this set of subclasses, and the complete implementation is left to subclasses.

Abstract classes can only be used as base classes, and implementations of their pure virtual functions are given by derived classes. if a derived class does not redefine a pure virtual function, and the derived class simply inherits the pure virtual function of the base class, the derived class is still an abstract class. If the implementation of the base class pure virtual function is given in the derived class, then the derived class is no longer an abstract class, it is a concrete class that can be used to create objects.

The rules of abstract classes

(1) An abstract class can only be used as a base class for other classes and cannot create abstract class objects.

(2) An abstract class cannot be used as a type for a parameter type, a function return type, or an explicit conversion.

(3) You can define a pointer and reference to an abstract class that can point to its derived class for polymorphism.

#include <iostream>using namespacestd;Const DoublePi=3.14159;classShapes//Abstract class{protected:    intx, y; Public:    voidSetValueintDintw=0) {x=d;y=W;} Virtual voidDisp () =0;//Pure virtual function};classSquare: Publicshapes{ Public:    voiddisp () {cout<<"Rectangular Area:"<<x*y<<Endl; }};classCircle: Publicshapes{ Public:    voiddisp () {cout<<"Circle Area:"<<PI*x*x<<Endl; }};intMain () {Shapes*ptr[2];//defining an array of object pointersSquare S1;    Circle C1; ptr[0] = &S1; ptr[0]->setvalue (Ten,5); ptr[0]->disp (); ptr[1] = &C1; ptr[1]->setvalue (Ten); ptr[1]->disp (); return 0;}

Three, similar concept:
1. Polymorphism
A different implementation action occurs when the same object receives different messages or when different objects receive the same message. C + + supports two kinds of polymorphism: compile-time polymorphism, run-time polymorphism.
A. Compile-time polymorphism: implemented by function overloading and operator overloading.
B Run-time polymorphism: implemented through inheritance and virtual functions.
2. Virtual function
A virtual function is a member function that is declared as virtual in a base class and redefined in a derived class to implement dynamic overloading of member functions
the declaration of a pure virtual function has a special syntax format: virtual return value type member function name (parameter table) =0;

Note that pure virtual functions should only be declared, without a specific definition, even if the definition of a pure virtual function is ignored by the compiler.

3. abstract class

Classes that contain pure virtual functions are called abstract classes. Because an abstract class contains a pure virtual function that is not defined, an object of an abstract class cannot be defined.
In C + +, we can set a class that is only used to be inherited and cannot create objects directly to abstract class.

The reason why an abstract class exists is that it has an element of uncertainty. We do exist in those classes, but the member functions in the parent class that are not able to determine the specific implementation are called pure virtual functions. Pure virtual function is a special virtual function, it only declares, there is no specific definition. At least one pure virtual function exists in an abstract class, and a class with a pure virtual function must be an abstract class . Existence of pure virtual function is a necessary and sufficient condition for becoming abstract class.

//base class:classa{ Public: A (); voidF1 (); Virtual voidF2 (); Virtual voidF3 () =0; Virtual~A ();};//sub-class:classD | Publica{ Public: B (); voidF1 (); voidF2 (); voidf3 (); Virtual~B ();};//Main function:intMainintargcChar*argv[]) {A*m_j=NewB (); M_j-F1 (); M_j-F2 (); M_j-f3 (); DeleteM_j; return 0;}/*F1 () is a normal overload. Call M_J->F1 (); Call the F1 () in Class A, which is set when we write the code. Because F1 () is not a virtual function, it is not dynamically bound, that is, it is defined by the Class A, so that the function of the class is called. F2 ( ) is a virtual function. Call M_j->f2 (); the function that corresponds to the object stored in M_j is called. This is due to the B object of New. F3 () is just like F2 (), except that the write function implementation is not required in the base class .*/

Virtual functions and pure virtual functions differ in the following ways.

(1) If the virtual function is declared in the class, the function is implemented, even if it is an empty implementation, it is to enable the function in its subclass can be overwritten, so that the compiler can use late binding to achieve polymorphism. Pure virtual function is only an interface, is a function of the declaration, it is to be left in the subclass to achieve.
(2) Virtual functions may not be overloaded within subclasses, but pure virtual functions must be implemented in subclasses, just like Java interfaces. It is a good practice to add a lot of functions to virtual, although sacrificing some performance, but increasing the object-oriented polymorphism, because it is difficult to anticipate that this function inside the parent class does not modify its implementation in the subclass.
(4) A class with a pure virtual function is called a virtual base class, and the base class cannot be used without directly generating the object, but only if it is inherited and overrides its virtual function. Such a class is also called an abstract class. Abstract class and we often say that the virtual base class is still different, in C # in the abstract definition of class, and in C + + has the concept of abstract class, but there is no such keyword. After the abstract class is inherited, the subclass can continue to be an abstract class, or it can be a normal class, and the virtual base class, is a class containing pure virtual function, if it is inherited, then the subclass must implement all the pure virtual function inside the virtual base class, its subclass can not be abstract class.

Threethe difference between an abstract class and an interface:
1. A class is an abstraction of an object, which can be understood as a class as an object, an abstract class called an abstract class.While the interface is just a specification or regulation of a behavior, Microsoft's custom interface is always back withAble field, proving that it is a class of expression"I can do ...". Abstract classes are more defined in a series of tightly related classes, whereas interfaces are mostly in classes where relationships are loose but they all implement a function.
2. Interface basically does not have any specific characteristics of inheritance, it promises only the methods that can be called.;
3. A class can implement several interfaces at a time, but only one parent class can be extended
4. Interfaces can be used to support callbacks, and inheritance does not have this feature.
5. Abstract classes cannot be sealed.
6. The concrete method of the abstract class implementation defaults to virtual, but the interface method in the class that implements the interface defaults to non-virtual, and of course you can declare it as virtual.
7. (interfaces) similar to non-abstract classes, an abstract class must also provide its own implementation for all members of the interface listed in the base class list of the class. However, an abstract class is allowed to map an interface method to an abstract method.
8. Abstract classes implement a principle in oop, separating mutable from immutable. Abstract classes and interfaces are defined as immutable, and the variable seating subclass is implemented.
9. A good interface definition should be functional, not multi-functional, or cause interface pollution. If a class just implements one of the functions of this interface, and has to implement other methods in the interface, it is called interface pollution.
10. Try to avoid using inheritance to implement the build function, but instead use black box multiplexing, which is the object combination. Because of the increasing level of inheritance, the most immediate consequence is that when you call one of these classes, you have to load them all into the stack! The consequences are conceivable . (in conjunction with the stack principle). At the same time, the heart of friends can notice that Microsoft in the construction of a class, many times the use of the object combination method. For example, in ASP. NET, thepage class has properties such as Server request, but in fact they are all objects of a class. Using This object of the page class to invoke the methods and properties of another class is a very basic design principle.
11. If an abstract class implements an interface, it is possible to map a method in an interface to an abstract class as an abstract method without having to implement the method in the subclass of the abstract class .

C + + abstract class

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.