First, overview:
Object-oriented programming is based on three basic concepts: data abstraction, inheritance and dynamic binding ;
In C + +, you use classes for data abstraction, and class derivation to inherit another class from one class: Derived classes inherit the members of the base class;
Polymorphism: Dynamic binding enables the compiler to decide at run time whether to use a function defined in a base class or a function defined in a derived class;
The key idea of object-oriented programming is polymorphism (polymorphism), realizing polymorphism must pass: 1, inherit 2, dynamic binding
Dynamic binding enables you to write programs that use any type of object in an inheritance hierarchy without caring about the object's specific type. Programs that use these classes
It is not necessary to distinguish whether a function is defined in a base class or in a derived class;
In C + +, dynamic binding occurs when a virtual function is called through a reference (or pointer) to a base class. The fact that a reference (or pointer) can point either to a base class object or to a derived class object is the key to dynamic binding. A virtual function called with a reference (or pointer) is determined by the run, and the function being called is defined by the actual type of the object referred to by the reference (or pointer);
1 voidPrintConst Base&Item, size_t N)2 {3OS << item.net_price (n) <<Endl;4 }5 /*6 *base base1;7 *diver Diver1; Diver inherit base;8 *9 * Net_price (size_t t) is virtual in base and implemented (non-pure virtual function)Ten * Net_price (size_t t) function is also implemented in diver. One * A * is the Net_price () or Net_price () in a derived class called in the base class in print? - * This is determined by the program at run time, the key is to see the parameter base& reference - * Is it a pointer to a base class object, or to a derived class object, to be directly determined; the * (The basis for implementation is that a reference to a base class can point to a base class object or to a derived class object) - */
1 classitem_base{2 Public:3Item_base (ConstSTD::string&book="",4 DoubleSales_price=0.0):5 ISBN (book), Price (Sales_price)6 {7 }8 9STD::stringBook ()ConstTen { One returnISBN; A } - Virtual DoubleNet_price (std::size_t N)Const - { the returnNPrice ; - } - Virtual~item_base () - { + } - Private: + Private: ASTD::stringISBN; at protected: -STD::stringISBN; - protected: - } - Private: -STD::stringISBN; in protected: - DoublePrice ; to } + /*In addition to constructors, any non-static member function can be a virtual function (destructors are best added with virtual). - * Reserved words can only appear in member function declarations inside a class, and cannot be used on function definitions that occur outside the body of a class definition; the */
C + + Object-oriented programming