The key idea behind OOP is polymorphism. As we'll see, in C++, polymorphism applies only to references or pointers to types related by inheritance.
Inheritance lets us define classes that model relationships among types, sharing what is common and specializing only that which is inherently different.
Dynamic binding lets us write programs that use objects of any type in an inheritance hierarchy without caring about the objects' specific types.
Note: In C++, dynamic binding happens when a virtual function is called through a reference (or a pointer) to a base class. The fact that a reference (or pointer) might refer to either a base- or a derived-class object is the key to dynamic binding. Calls to virtual functions made through a reference (or pointer) are resolved at run time: The function that is called is the one defined by the actual type of the object to which the reference (or pointer) refers.
Virtual destructor It is worth noting that classes used as the root class of an inheritance hierarchy generally define a virtual destructor.
Virtual functions
1) Purpose: The purpose of the virtual keyword is to enable dynamic binding. By default, member functions are nonvirtual. Calls to nonvirtual functions are resolved at compile time.
2) Rule: A base class usually should define as virtual any function that a derived class will need to redefine.
3) Scope: Any nonstatic member function, other than a constructor, may be virtual. The virtual keyword appears only on the member-function declaration inside the class. The virtual keyword may not be used on a function definition that appears outside the class body.
Virtual function in derived class: Once a function is declared as virtual in a base class it remains virtual; nothing the derived classes do can change the fact that the function is virtual. When a derived class redefines a virtual, it may use the virtual keyword, but it is not required to do so.
Inheritance vs Composition:
Inheritance should reflect a so-called "Is A" relationship of the derived class to the base class. In our bookstore example, our base class represents the concept of a book sold at a stipulated price. Our Bulk_item is a kind of book, but one with a different pricing strategy.
Composition among types is a so-called "Has A" relationship. Our bookstore classes have a price and they have an ISBN. Types related by a "Has A" relationship imply membership. Thus, our bookstore classes are composed from members representing the price and the ISBN.
Operator Overloading and Friendship
To support:
cout << item1 + item2 << endl;
we need the following definition:
class Sales_item {
friend std::istream& operator>>
(std::istream&, Sales_item&);
friend std::ostream& operator<<
(std::ostream&, const Sales_item&);
public:
Sales_item& operator+=(const Sales_item&);
};
Sales_item operator+(const Sales_item&, const Sales_item&);
Wednesday, October 8, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment