Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 159.234LECTURE 15 159.234 LECTURE 15 Inheritance Text book p.273-298.

Similar presentations


Presentation on theme: "1 159.234LECTURE 15 159.234 LECTURE 15 Inheritance Text book p.273-298."— Presentation transcript:

1 1 159.234LECTURE 15 159.234 LECTURE 15 Inheritance Text book p.273-298

2 2 We frequently classify objects according to some common properties. Mammals have properties such as: warm-blooded higher vertebrates These properties are valid for both an elephant and a mouse, but it is best if we only have to express it only once for all mammals and not have to duplicate for every mammal. Using inheritance, a large body of knowledge can be presented in a more compact way.Inheritance

3 3 cat The class cat is derived from the class mammal. We say that a cat “is a mammal” and is also a “living creature”. But a cat “is not a reptile”. It is often useful to build our Object-Oriented programs this way. mammal elephant reptile snake cat living creaturesInheritance

4 4 Sphere Shape TwoDThreeD Circle Rectangle Parent, or base class Child, or derived class How can we code our objects like this? Inheritance

5 5 #include using namespace std; const static double PI = 3.141592654; class Shape{ // base class private: char * label; // a string label for the shape }; class TwoD : public Shape{ // two dimensional shapes private: double x, y; }; class ThreeD : public Shape{ // three dimensional shapes private: double x, y, z; }; class Circle : public TwoD{ // Circle extends TwoD public: double area() { return PI * radius * radius; } private: double radius; }; class Rectangle : public TwoD{ public: double area(){ return width * height; } private: double width, height; }; class Sphere : public ThreeD{ public: double volume() { return 4.0 / 3.0 * PI * radius * radius * radius; } private: double radius; }; int main(){ Sphere s1; Circle c1; Shape* shptr; shptr = & s1; shptr = & c1; return 0; } skeleton code!. No output - this is only a skeleton code!. public inheritance Note the public inheritance relations between the classes. base class derived Shape is the base class, and TwoD and ThreeD are derived from it We can group information (and avoid having to duplicate code) in a way that reflects our application and the real things or ideas that our code models. derived Note that in main, a Shape pointer can point to any object that is derived from it.

6 6 parent For the parent (of class Circle) we might write: class TwoD : public Shape{ public: void print(){cout<< x;} //... protected protected: double x,y; //... }; protected : protected : the data of the class is accessible from within the class itself, to its friend classes, derived classes and their friend classes (derived classes’ friend classes), but not in any other part of the program.Inheritance

7 7 For the parent class of Circle we write: TwoD class TwoD :public Shape{ public: print() void print(){cout<<…;} //.. protected: x, y double x, y; //.. }; derived class For the derived class we write: Circle:public TwoD class Circle :public TwoD{ public: double area(); private: double radius; }; print() public print() and xy Circle protected x and y, are now also part of Circle (inherited from the parent).Inheritance

8 8 public inheritance This is called public inheritance. public protected public and protected data of the parent class are inherited in the derived class, and have the same access type. We can have private and protected inheritance as well - we will look at those later. Public inheritance is the most commonly used. :public TwoD class Circle :public TwoD { public: double area(); private: double radius; };Inheritance Next, let’s modify the hierarchy of classes we saw earlier...

9 9 #include using namespace std; const static double PI = 3.141592654; class Shape{ // base class private: char * label; // a string label for the shape }; class TwoD : public Shape{ // two dimensional shapes protected: double x, y; }; class ThreeD : public Shape{ // three dimensional shapes protected: double x, y, z; }; class Circle : public TwoD{ // Circle extends TwoD public: double area(){ return PI * radius * radius; } private: double radius; }; class Rectangle : public TwoD{ public: double area(){ return width * height; } private: double width, height; }; class Sphere : public ThreeD{ public: double volume() { return 4.0 / 3.0 * PI * radius * radius * radius; } private: double radius; }; int main(){ Sphere s1; Circle c1; cout << "size of s1 is " << sizeof(s1) << endl; cout << "size of c1 is " << sizeof(c1) << endl; return 0; } Example Output: size of s1 is 36+4 size of c1 is 28+4 40 = 4 (char *) + 3 * 8 (double) + 8 (double) + 4 (Class) 32 = 4 (char*) + 2 * 8 (double) + 8 (double)+ 4 (Class) label xy Circles inherit label and x and y labelx, yz Spheres inherit label, x, y and z class incurs an extra overhead

10 10 Inheritance: Visibility Modifiers Public inheritance: public in base-> public in derived protected-> protected cannot be accessed private-> cannot be accessed Protected inheritance: public in base-> protected in derived protected-> protected cannot be accessed private-> cannot be accessed Private inheritance: public in base-> private in derived protected-> private cannot be accessed private-> cannot be accessed private Default inheritance if not explicitly specified: private

11 11Inheritance Stud class Stud { public: Stud(char *s, int id); void print(); protected: int stud_id; char surname[64]; }; We can create a new type Grad from Stud with added information : GradpublicStud class Grad : public Stud { public: Grad(char *s, int id, char *t); void print(); protected: char thesis[64]; }; Notice that each class has its own constructor.

12 12Inheritance Stud Stud:: Stud(char *s, int id) { strcpy(surname,s); stud_id = id; } Gradsid:Stud(s, id) Grad::Grad(char *s, int id, char *t) : Stud(s, id) { strcpy(thesis, t); } initialiser list Grad The constructor for Stud is placed in the initialiser list of the Grad constructor. How do we get initialisation of the information?

13 13Inheritance It is possible to redefine functions (override) in the derived class to alter its behaviour. print() is defined in both Stud and Grad. print void Stud::print() { cout << surname << " " << stud_id; } print void Grad::print() { Stud::print(); Stud::print(); cout << " " << thesis; } We must use the scope operator, otherwise we get a recursive call. Which function is used is decided at compile time - depending on the type of the object.

14 14Inheritance derived TwoD If we have many objects derived from the type TwoD and need to calculate their total area: pointers We could store pointers to them in an array. Then work through the array to calculate the total area. Circle c, d Circle c, d; Recte, f Rect e, f; TwoDp TwoD *p[4]; pcpdpepf p[0]=&c; p[1]=&d; p[2]=&e; p[3]=&f; Circle Rect derivedTwoD This is allowed because Circle and Rect are both derived from TwoD.

15 15Inheritance Now loop through the array: for (int i=0;i<4;i++) { parea() total += p[i]->area(); } Does this work? Yes, if we create virtual functions!

16 16Polymorphism TwoD class TwoD { public: TwoD(double a, double b) : x(a), y(b) {} virtualareareturn 0; virtual double area(void) {return 0;} protected: double x,y; }; area()virtual area() is a called a virtual function.

17 17Polymorphism Rect TwoD class Rect : public TwoD{ public: Rect Rect(double a, double b, double ht, double wd) TwoD : TwoD(a,b), h(ht), w(wd) {} virtualreturn w * h; virtual double area(void) {return w * h;} private: double h,w; }; area()virtual area() is a called a virtual function.

18 18Polymorphism Circle TwoD class Circle : public TwoD{ public: Circle(double a, double b, double rad) : TwoD(a,b), r(rad) {} virtualreturn PI*r*r; virtual double area(void) {return PI*r*r;} private: double r; }; area is a called a virtual function.

19 19Polymorphism virtual area() is called a virtual function. knows the types of objects that pointers point to The run-time system knows the types of objects that pointers point to! The appropriate function is called when we ask for p[i]->area() for (int i=0;i<4;i++) { p[i]->area() total += p[i]->area(); } Here’s the code segment again: Circle c, d; Rect e, f; TwoD* p[4]; p[0]=&c; p[1]=&d; p[2]=&e; p[3]=&f; dynamic binding This is called dynamic binding. The binding of the call to the actual code to be executed is deferred until run-time.

20 20Destructors derived new/delete. Be careful with derived objects created on the heap using new/delete. If we delete an object through a base-class pointer delete p[i]; base class virtual Then only the destructor of the base class will be called! Not unless it is declared virtual. base class virtual functions destructorshould also be virtual As a general rule, if a base class contains virtual functions, then the destructor in the base class should also be virtual. See Virtual Destructor - Memory Leak Resolved.cpp

21 21 Abstract Base Classes Sometimes we want to declare a class, but only allow a programmer to create objects of its derived classes. TwoD circle rect TwoD TwoD TwoD can be made into an abstract class. We can create objects of its derived classes, circle and rect. We can create pointers to the TwoD class. But, we can not create an object of type TwoD. 'pure virtual function The compiler will not allow an object to be created if a class contains a 'pure virtual function '.

22 22 Pure Virtual Function class TwoD { public: TwoD(double a, double b) : x(a), y(b) {} virtual double area(void) = 0; protected: double x, y; };

23 23 Multiple Inheritance class Student { public: name char name[32]; char id[10];... }; class Worker { public: name[32 char name[32]; char ird_no[13];... }; Lab_Tutor class Lab_Tutor : public Student, public Worker {... }; Derived classes can have more than one base class:

24 24Inheritance Lab_Tutor Lab_Tutor A; A.Student:: strcpy(A.Student::name, “Napoleon");... The scope operator is used to resolve name clashes.

25 25 Virtual Inheritance to remove the ambiguity If we want to remove the ambiguity, we can make the inheritance 'virtual'. class Person { public: char name[32]; }; class Student : virtual public Person { public: char id[10];... }; or public virtual Person

26 26 Virtual Inheritance class Worker : virtual public Person { public: char ird_no[13];... }; class Lab_Tutor : public Student, public Worker {... }; Now there is only one name associated with Lab_Tutor: Lab_Tutor A; name strcpy(A.name, “Itchy");... class Person { public: char name[32]; }; class Student : virtual public Person { public: char id[10];... };

27 27 See Demo Codes: virt_err.cpp virt_sel2.cpp abstract.cpp Sample Codes

28 28 #include using namespace std; class B { public: virtual void foo(int i) {cout<<"\n In Base " << i;} virtual void foo(double d){cout<<"\n In Base "<< d;} }; class D : public B { public: void foo(int k) {cout<<"\n In derived " <<k;} }; int main(){ D d; B b, *pb = &d; b.foo(9); //selects B::foo(int); b.foo(9.5); //selects B::foo(double); d.foo(9); //selects D::foo(int); d.foo(9.5); //selects D::foo(int); // here, the function foo() in class //d is called because we are accessing //the object directly pb -> foo(9); //selects D::foo(int); pb -> foo(9.5); //selects B::foo(double); return 0; } virt_err.cpp Output: In Base 9 In Base 9.5 In derived 9 In Base 9.5

29 29 #include using namespace std; //virtual function selection class B { public: int i; virtual //comment this out-see what is the result! void print_i() const { cout << i << " inside Base class" << endl; } }; class D : public B { public: //virtual as well void print_i() const { cout << i << " inside Derived class" << endl; } }; int main() { B b; B* pb = &b; //points at a B object D f; D& g=f; f.i = 1 + (b.i = 1); B pb -> print_i(); //call B::print_i() D pb = &f; //points at a D object D pb -> print_i(); //call D::print_i() D g.print_i(); //call D::print_i() } virt_sel2.cpp Output: 1 inside Base class 2 inside Derived class

30 30 Output (non-virtual): 1 inside Base class 2 inside Base class 2 inside Derived class #include using namespace std; //virtual function selection class B { public: int i; void print_i() const { cout << i << " inside Base class" << endl; } }; class D : public B { public: void print_i() const { cout << i << " inside Derived class" << endl; } }; int main() { B b; B* pb = &b; //points at a B object D f; D& g=f; f.i = 1 + (b.i = 1); B pb -> print_i(); //call B::print_i() D pb = &f; //points at a D object D pb -> print_i(); //call D::print_i() D g.print_i(); //call D::print_i() }

31 31 Let’s take a peek at how the compiler is actually implementing virtual inheritance.

32 32 Virtual Inheritance No classes actually contain the virtual base class. Instead, they hold a pointer to a virtual base class table that tells them where in the object the virtual base class exists. ColorListStruct ColorListStruct Base Table Source: Efficient C/C++ Coding Techniques Embedded Systems Conference Boston 2001 Class 304

33 33 Multiple Virtual Inheritance Each level of virtual inheritance requires its own virtual base table. Source: Efficient C/C++ Coding Techniques Embedded Systems Conference Boston 2001 Class 304

34 Additional References 34 Technical Report on C++ Performance ISO/IEC TR 18015:2006(E) Next: Inheritance Mastering Visual C++ http://www.cplusplus.com/reference/iostream/ios/bad.html Efficient C/C++ Coding Techniques Embedded Systems Conference Boston 2001 Class 304

35 35 Inheritance is the mechanism of deriving new classes from old ones. Through inheritance, a hierarchy of related, code-sharing abstract data types (ADT’s) can be created. The keywords public, private, and protected are used as visibility modifiers for class members. Next:More on inheritance Abstract classesSummary


Download ppt "1 159.234LECTURE 15 159.234 LECTURE 15 Inheritance Text book p.273-298."

Similar presentations


Ads by Google