Inheritance C++ strongly support the reusability, that is one class has been written and tested already it can be adapted or used to create a new class.

Slides:



Advertisements
Similar presentations
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Advertisements

Operator Overloading Fundamentals
Learners Support Publications Inheritance: Extending Classes.
Inheritance, Polymorphism, and Virtual Functions
Operator overloading Object Oriented Programming.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
Operator Overloading and Type Conversions
Chapter 12: Adding Functionality to Your Classes.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Polymorphism &Virtual Functions
Polymorphism &Virtual Functions 1. Polymorphism in C++ 2 types ▫Compile time polymorphism  Uses static or early binding  Example: Function and operator.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Operator overloading and type convesions BCAS,Bapatla B.mohini devi.
Operator Overloading. Introduction It is one of the important features of C++ language  Compile time polymorphism. Using overloading feature, we can.
Unit: 7 Operator Overloading and Type Conversions Course: MBATech Trimester: II.
Operator Overloading Operator Overloading allows a programmer to define new types from the built-in types. –Operator Overloading is useful for redefining.
Topic 1 11/18/2015. Submitted By: Arslan Ali : Roll No: 6703 Ali Ahmad : Roll No: 6710 Ameer Moavia : Roll No: 6734 Abdul Manam : Roll No: 6738 Agha Waqas.
CSC241 Object-Oriented Programming (OOP) Lecture No. 4.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Inheritance: Base and Derived Classes. Introduction In dictionary inheritance is defined as the action of inheriting; the transfer of property; to receive.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
CONSTRUCTOR AND DESTRUCTORS
Operator overloading: Overloading a unary operator is similar to overloading a binary operator except that there is one Operand to deal with. When you.
Chapter -6 Polymorphism
Unit VI polymorphism. Md.Jaffar Sadiqsumalatha Polymorphism refers to : one name, many forms. Polymorphism is of two types:  Compile time polymorphism.
Learning Objectives Fundamentals of Operator Overloading. Restrictions of Operator Overloading. Global and member Operator. Overloading Stream-Insertion.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
Asif Nawaz University Institute of Information Technology, PMAS-AAUR Lecture 07: Object Oriented Programming:2014 Object-Oriented Programming in C++ Operator.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Operator Overloading Ritika Sharma.
Modern Programming Tools And Techniques-I
Inheritance.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
7. Inheritance and Polymorphism
Inheritance-Basics.
Inheritance and Polymorphism
Operator Overloading.
Polymorphism &Virtual Functions
Inheritance, Polymorphism, and Virtual Functions
Inheritance and Run time Polymorphism
Objectives Define polymorphism Overload functions
Polymorphism & Virtual Functions
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Inheritance C++ strongly support the reusability, that is one class has been written and tested already it can be adapted or used to create a new class.
Operator Overloading BCA Sem III K.I.R.A.S.
Polymorphism Lec
Modern Programming Tools And Techniques-I Inheritance
Virtual Functions Department of CSE, BUET Chapter 10.
Inheritance Dr. Bhargavi Goswami Department of Computer Science
Inheritance, Polymorphism, and Virtual Functions
Constructor Spl member fn auto ini of object
Polymorphism Polymorphism
Operator overloading Dr. Bhargavi Goswami
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
Virtual Functions Polymorphism is supported by C++ both at compile time and at run time. Compile-time polymorphism is achieved by overloading functions.
POLYMORPHISM ( in C++) POLYMORPHISM ( in C++). Presentation Outline Polymorphism Definition Types – Compile time and Run time polymorphism Function overloading.
C++ Inheritance.
Inheritance:Concept of Re-usability
Overview of C++ Polymorphism
Institute of Petroloeum Technology, Gandhinagar
Inheriting Multiple Base Classes
C++ Object Oriented 1.
Computer Science II for Majors
Presentation transcript:

Inheritance C++ strongly support the reusability, that is one class has been written and tested already it can be adapted or used to create a new class. The reusable property will reduce the debugging time . The time overhead and cost overhead will be reduced. Thus, the reusability mechanism is apply to the Inheritance

Inheritance Definition: The mechanism of deriving a new class from an old one is called inheritance. The old class is referred to as the base class and the new one is called derived class.

a)Single inheritance : Types of Inheritance a)Single inheritance : A derived class with only one base class. b)Multiple inheritance: A class with several base classes. A B A B C

c)Hierarchical inheritance: Derivation of several classes from a single base class. d)Multilevel inheritance: Derivation of a class from another derived class is called Multilevel inheritance A B C D A B C

E)Hybrid inheritance: Derivation of a class involving more than one form of inheritance is called hybrid inheritance A B C D

f)Multipath inheritance: Derivation of a class from other derived classes which are derived from same base class. A B C D

Defining derived classes A derived class is defined by specifying its relationship with the base class in addition to its own details. Syntax: Class derived-classname: visibility mode base- classname { //members of derived class }; : indicates derived class is derived from the class, visibility mode is optional(by default it is private) it may private or public.

Example: class X:private Y // private inheritance (or) private derivation { Members of X }; class X:public Y // public derivation class X: Y // private derivation by default

Example program #include <iostream Example program #include <iostream.h> class A { protected: int data; public: void getdata(int x) data1 = x; } }; class B: public A void setdata(int y) data2 = y;

void display( ) { cout<<”data1”<<data1; cout<<”data2”<< data2;  }; void main( ) B s; s.getdata(10); s.setdata(20); s.display( ); } Explanation: The new class ‘B’ can be derived by the base class ‘A’. The base class A publicly inherited to a derived class ‘A’.

PROTECTED: The protected data members will be accessible by its own class and which class is immediately derived from its that class also have the rights to access the protected data member (will be act as protected data member of a derived class also). In the program, using the derived class object we can access the member function of getdata and setdata giving the value of data1 and data2. In the display function multiply the value of data1 and data2 and display the result.

Multilevel inheritance The multilevel inheritance is defined as, the new class is derived from another derived class.   Fig: Multilevel Inheritance Here the class A serves as a base class for the derived class B which in turn serves as a base class for the derived class C. A B C

Syntax for Multilevel Inheritance class A { //body of base class A }; class B : public A { //body of intermediate base class B class C : public B { //body of derived class

Example Program-Multilevel #include <iostream Example Program-Multilevel #include <iostream.h> class student { protected: int rollno: public: void getroll(int x) rollno = x; } }; void test: public student float sub1, sub2; void getmart(int y, int z) sub1 = y; sub2= z;

void result : public test { float total; public: void display( ) total = sub1 + sub2; cout<<rollno<<sub1<<sub2; cout<<total; } }; void main( ) result s; s.getroll(101); s.getmark(90, 100); s.display( );

Multiple inheritance A class can inherit the attributes or properties of two or more classes that is a new class can be derived from more than one base class is called multiple inheritance. Here the class A and class B serves as a base class for the derived class C. The derived class definition syntax is: class c: visibility base-1, visibility base 2,… { body of class c; }; A B C

Example: class A { protected: int rollno; public: void getroll(int x) #include<iostream.h> class A { protected: int rollno; public: void getroll(int x) rollno=x; } }; class B int sub1,sub2; void getmark(int y,int z)\ sub1=y; sub2=z;  

class C : public A, public B { int total; public: void display() total=sub1+sub2; cout<<”roll no:”<<rollno<<”sub1:”<<sub1<<”sub2:”<<sub2; cout<<”total”<<total; } }; void main() C s; s. getroll(435); s.getmark(100,90); s.display(); Run: Roll no : 435 Sub1: 100 Sub2: 90

hybrid inheritance The hybrid inheritance is defined as a combination of multilevel and multiple inheritances. This new class can be derived by either multilevel or multiple method or both. A B C D

Student Multilevel Test Sports Multiple Result

#include <iostream #include <iostream.h> class student { protected: int rollno; public: void getroll (int x) rollno = x; } }; class test: public student int sub1, sub2’ void getmark (int y, int z) sub1 = y; sub2 = z;

class sports { protected: int score; public: void getscore (int a ) score=a; } }; class result: public test, public sports int total; void display() total= sub1+sub2+score; cout<<”rollno:”<<rollno<< “total:”<<”Score:”<<total;

void main( ) { result S; s.getroll(101); s.getmark(90,98); s.getscore(2000); s. display( ); } Run: Rollno: 101 Total: 188 Score: 2000

Virtual base class(Multipath inheritance) The form of inheritance which derives a new class by multiple inheritance of base classes, which are derived earlier from the same base class, is known as multipath inheritance. It involves more than one form of inheritance namely multilevel, multiple and hierarchical. All the public and protected members of “grandparent” are inherited into “child” twice, first via “parent1” and again via “parent 2”.This means “child” would have duplicate sets of the members inherited from “grand parent”.

The duplication of the inherited members due to these multiple paths can be avoided by making the common base class as virtual base class while declaring the direct or intermediate base classes.

Type conversion or Type casting Types: Implicit type conversion(Automatic) Lower order to higher order Explicit type conversion(Manual) Higher order to lower order.

Three types in the data conversion: Conversion from basic type to class type. Conversion from class type to basic type. Conversion from class type to class type.

Conversion from basic type to class type Conversion from basic type to class type. CLASS Object=class member variable; Note: Conversion takes place in constructor.

Converting an basic type to a class type class distance { private: int kilometer; public: distance(double mile) double km=kilometer; } void display(void) cout<<kilometres<<“kilometer\n”; }; void main() clrscr(); distance d=5.0; cout<<“miles”; d.display(); getch(); }

Conversion from class type to basic type class member variable =CLASS Object; Syntax: operator type name() { //function statements return (); } Note: Conversion takes place in overloading casting operator.

The constructor handles the task of converting basic types to class types very well. But cant use constructors for converting class to basic types. Instead ,we can define an overloaded casting operator that can be used to convert a class into a basic type. Casting operator function is known as a conversion function. Conditions: Overloaded casting operator: It must be a class member. It must not specify a return type. It must not have any argument

Eg: class A { private: int km; public: A(int miles) km=miles; } operator int() return(miles/1000); void display() cout<<Km; };

void main() { A d(50); int m1=d; cout<<m1; }

Conversion from class type to class type Object1=Object2; Note: Conversion takes place in overloading casting operator and Constructor.

# include<iostream # include<iostream.h> class invent2 ; \\ destination class declared class invent1 { int code; public: invent1(int a) code =a; } void putdata() cout<<“code:”<<code; int getcode() return code; };

class invent2 { int code; float value; public: invent2() code=0; value=0; } void putdata() cout<<“code:”<<code; cout<<“value:”<<value; invent2(invent1 p) code=p.getcode(); };

int main() { invent1 s1(100); invent2 d1; float total_value; total_value=s1; \\invent1 to float \\ variable =object (type 2) d1=s1; \\invent1 to invent2 cout<<“Product details –invent1 type”; s1.putdata(); cout<<“Product details –invent2 type”; d1.putdata(); return 0; }

Virtual functions A virtual function is a member function that is declared within a base class and redefined by a derived class. To create a virtual function, precede the function's declaration in the base class with the keyword virtual. Virtual functions implement the "one interface, multiple methods" philosophy that underlies polymorphism. A pointer to an object of a base class can also point to the object of its derived classes. A base-class pointer can be used to point to an object of any class derived from that base.

When a base pointer points to a derived object that contains a virtual function, C++ determines which version of that function to call based upon the type of object pointed to by the pointer. And this determination is made at runtime.

#include <iostream> class base { public: virtual void vfunc() { cout << "This is base's vfunc().\n"; } }; class derived1 : public base { void vfunc() { cout << "This is derived1's vfunc().\n"; int main() { base *p, b; derived1 d1; // point to base p = &b; p->vfunc(); // access base's vfunc() // point to derived1 p = &d1; p->vfunc(); // access derived1's vfunc()

return 0; } This program displays the following: This is base's vfunc(). This is derived1's vfunc(). As the program illustrates, inside base, the virtual function vfunc() is declared. Notice that the keyword virtual precedes the rest of the function declaration. When vfunc() is redefined by derived1 and derived2, the keyword virtual is not needed. (However, it is not an error to include it when redefining a virtual function inside a derived class; it's just not needed.)

Next, p is assigned the address of b, and vfunc() is called via p Next, p is assigned the address of b, and vfunc() is called via p. Since p is pointing to an object of type base, that version of vfunc() is executed. Next, p is set to the address of d1, and again vfunc() is called by using p. This time p points to an object of type derived1. This causes derived1::vfunc() to be executed. The key point here is that the kind of object to which p points determines which version of vfunc() is executed. Further, this determination is made at run time, and this process forms the basis for run-time polymorphism.

Pure Virtual functions A pure virtual function is a virtual function that has no definition within the base class. To declare a pure virtual function, use this general form: virtual type func-name(parameter-list) = 0;

#include <iostream> class number { protected: int val; public: void setval(int i) { val = i; } // show() is a pure virtual function virtual void show() = 0; }; class hextype : public number { void show() { cout << hex << val << "\n"; class octtype : public number { cout << oct << val << "\n";

int main() { octtype o; hextype h; o.setval(20); o.show(); // displays 24 – octal h.setval(20); h.show(); // displays 14 – hexadecimal return 0; } when a virtual function is declared as pure, all derived classes must override it. If a derived class fails to do this, a compile-time error will result.

Abstract base class A class that contains at least one pure virtual function is said to be abstract. Because an abstract class contains one or more functions for which there is no definition (that is, a pure virtual function), no objects of an abstract class may be created. Although you cannot create objects of an abstract class, you can create pointers and references to an abstract class. This allows abstract classes to support run-time polymorphism, which relies upon base-class pointers and references to select the proper virtual function.

Syntax: class Base { public: virtual void funct()=0; };

#include <iostream> class shape { public: virtual void draw()=0; }; class Rectangle: public shape void draw(); class Circle: public shape

Operator Overloading An operator function defines the operations that the overloaded operator will perform relative to the class upon which it will work. An operator function is created using the keyword operator. The operator overloading feature of C++ is one of the methods of realizing polymorphism. C++ has the ability to provide the operators with a special meaning to an operator is known as operator overloading.

We can overload all the C++ operators except the following: Scope resolution operator(::) Size of operator(size of) Conditional operator(?:) Class member access operator(. , .* , →*) Pointer to member declarator(::*)

Operators that Can and Cannot be Overloaded Deitel & Deitel, Figure 22.1 Deitel & Deitel, Figure 22.2 Operator Overloading CS-2303, C-Term 2010

Non-Overloadable Operators Student Book Non-Overloadable Operators Operators that can not be overloaded due to safety reasons: Member Selection ‘.’ operator Member dereference ‘.*’ operator Exponential ‘**’ operator User-defined operators Operator precedence rules Exponential operator is reserved User-defined operators because of precedence problem

Rules The overloaded operator must have at least one operand that is user-defined type We cannot change the basic meaning of an operator. This is to say we cannot redefine the plus(+)operator to subtract one value from the other Overloaded operators follow the syntax rules of the original operators. They cannot be overridden. There are some operators that cannot be overloaded We cannot use friend function to overload certain operators. However member functions can be used to overload them.

Where a friend cannot be used = Assignment operator ()Function call operator [] Subscripting operator ->class member access operator

Student Book Types of Operator Unary operator Binary operator

Student Book Unary Operators Operators attached to a single operand (-a, +a, --a, a--, ++a, a++) The pre and post increment and decrement operators and overloading in different ways. This is because they have a different effect on objects and their values. e.g. a=14; cout << a++; // will print 14 and increment a cout << ++a; // will increment a and print 15

class space { int x,y,z; public: void getdata(int a,int b,int c); void display(void); void operator-(); }; void space::getdata(int a,int b,int c) x=a; y=b; z=c; } void space::display(void) cout<<x<<“ ”; cout<<y<<“ “; cout<<z<<“\n”;

void space::operator-() { x=-x; y=-y; z=-z; } int main() space s; s.getdata(10,-20,30); cout<<“s:”; s.display(); -s; return 0;

Student Book Binary Operators Operators attached to two operands (a-b, a+b, a*b, a/b, a%b, a>b, a>=b, a<b, a<=b, a==b)

class sample { private: int value; public: sample(int one); int operator+(sample obj b); void display(); }; sample::sample(int one) value=one; } int sample::operator+(sample obj b) return(value +obj b.value); void sample::display() cout<<“value:”<<value<<endl;

void main() { clrscr(); sample obj1(10); sample obj2(20); obj1 void main() { clrscr(); sample obj1(10); sample obj2(20); obj1.display(); obj2.display(); cout<<“value:”<<(obj1.operator+(obj2))<<endl; getch(); }

Using assignment operator class sample { private: int value; public: sample(int one); int operator=(sample obj b); void display(); }; sample::sample(int one) value=one; } int sample::operator=(sample obj b) return(value=obj b.value);

void sample::display() { cout<<“value:”<<value<<endl; } void main() clrscr(); sample obj1(10); sample obj2(20); obj1.display(); obj2.display(); cout<<“value:”<<(obj1.operator=obj2))<<endl; getch();

#include<iostream. h> #include<conio #include<iostream.h> #include<conio.h> class complex { int a,b; public: void getvalue() { cout<<"Enter the value of Complex Numbers a,b:"; cin>>a>>b; }

complex operator+(complex ob)               {                             complex t;                             t.a=a+ob.a;                             t.b=b+ob.b;                             return(t);               }

complex operator-(complex ob) { complex t; t. a=a-ob. a; t. b=b-ob complex operator-(complex ob) { complex t; t.a=a-ob.a; t.b=b-ob.b; return(t); } void display() cout<<a<<"+"<<b<<"i"<<"\n"; };

 void main() {    clrscr();    complex obj1,obj2,result,result1;     obj1.getvalue();    obj2.getvalue();     result = obj1+obj2;    result1=obj1-obj2;

cout<<"Input Values:\n"; obj1. display(); obj2 cout<<"Input Values:\n"; obj1.display(); obj2.display(); cout<<"Result:"; result.display(); result1.display(); getch(); }

Output: Enter the value of Complex Numbers a, b 4 5 2 2 Input Values 4                  5 2                  2 Input Values 4 + 5i 2 + 2i Result 6 +   7i 2 +   3i