Download presentation
Presentation is loading. Please wait.
Published byRoss Terry Modified over 9 years ago
1
CSCI-383 Object-Oriented Programming & Design Lecture 21
2
Approaches to Repeated Inheritance Either single or multiple copies of common base class Eiffel’s approach: decision made by designer of D C++’s approach: decision made by designer B and C A BC D
3
Approaches to Repeated Inheritance In C++ this problem is overcome through the use of the virtual modifier in the parent class list The virtual keyword indicates that the superclass may appear more than once in descendant classes of the current class but that only one copy of the superclass should be included class ios {... }; class istream: virtual public ios {... }; class ostream: virtual public ios {... }; class iostream: public istream, public ostream {... }; Handout #8 Handout #8
4
Planning for the Diamond Problem class Person {... void print(ostream& out){ // Print person data (e.g., name, gender, etc) } }; class Student: virtual public Person {... void print(ostream& out){ Person::print(out); // Print student data (e.g., courses, year, etc) } };
5
Planning for the Diamond Problem class Teacher: virtual public Person {... void print(ostream& out) { Person::print(out) // Print teacher data (e.g., salary, courses, etc) }; class TeachingAssistant: public Student, public Teacher {... void print(ostream& out) { Student::print(out); Teacher::print(out); // Print assistant data (e.g., supervisor, etc) }; Do you see any problem? Fix this problem (DONE IN CLASS)
6
Cross Delegation Handout #9 Handout #9 Notice how, in handout #9, a class that DerivedOne knows nothing about will supply the override of a virtual function invoked by DerivedOne::foo()handout #9 This “cross delegation” can be a powerful technique for customizing the behavior of polymorphic classes
7
Constructors and Virtual Base Class? class V { public: V(const char* s){ cout << s;} }; class B1: virtual public V{ public: B1(const char* s):V(“B1”){ cout << s;} }; class B2: virtual public V{ public: B2(const char* s):V(“B2”){ cout << s;} }; class D: public B1, public B2 { public: D(void):B1(“DB1”),B2(“DB2”) {} }; What will be printed when instantiating object of class D ?
8
Construction of a Virtual Base Class Work around 1 Define a default constructor in V Work around 2 Call V ’s constructor directly from the constructor of D Virtual bases are initialized by the initializer of the most derived class, other initializers are ignored Virtual bases may be initialized in a constructor of a derived class even if they are not immediate base classes Practically speaking, this means that when you create a class that has a virtual base class, you must be prepared to pass whatever parameters are required to call the virtual base class's constructor This might mean that the most-derived class's constructor needs more parameters than you might otherwise think
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.