Download presentation
Presentation is loading. Please wait.
Published byJerome Bryan Modified over 6 years ago
1
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
2
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.
3
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
4
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
5
E)Hybrid inheritance:
Derivation of a class involving more than one form of inheritance is called hybrid inheritance A B C D
6
f)Multipath inheritance:
Derivation of a class from other derived classes which are derived from same base class. A B C D
7
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.
8
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
9
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 private: void setdata(int y) data2 = y;
10
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’.
11
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.
12
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
13
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
14
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;
15
void test: public student { protected: float sub1, sub2; public: void getmart(int y, int z) sub1 = y; sub2= z; } }; void result : public test float total; void display( ) total = sub1 + sub2; cout<<rollno<<sub1<<sub2; cout<<total;
16
void main( ) { result s; s. getroll(101); s. getmark(90, 100); s
void main( ) { result s; s.getroll(101); s.getmark(90, 100); s.display( ); }
17
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
18
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;
19
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
20
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
21
Student Multilevel Test Sports Multiple Result
22
#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;
23
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;
24
void main( ) { result S; s.getroll(101); s.getmark(90,98); s.getscore(2000); s. display( ); } Run: Rollno: 101 Total: 188 Score: 2000
25
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”.
26
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.
27
Type conversion or Type casting
Types: Implicit type conversion(Automatic) Lower order to higher order Explicit type conversion(Manual) Higher order to lower order.
28
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.
29
Conversion from basic type to class type
Conversion from basic type to class type. Object=class member variable; Note: Conversion takes place in constructor.
30
Converting an basic type to a class type
class distance { private: int kilometer; public: distance(double mile) double km=kilometers; } void display(void) cout<<kilometres<<“kilometer\n”; }; void main() clrscr(); distance d=5.0; cout<<“miles”; d.display(); getch(); }
31
Conversion from class type to basic type
class member variable =Object; Syntax: operator type name() { //function statements return (); } Note: Conversion takes place in overloading casting operator.
32
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
33
Eg: class A { private: int km; public: A(int miles) km=miles; } operator int() return(miles/1000); void display() cout<<Km; };
34
void main() { A d(50); int m1=d; cout<<m1; }
35
Conversion from class type to class type Object1=Object2; Note: Conversion takes place in overloading casting operator and Constructor.
36
# 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; };
37
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(); };
38
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; }
39
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.
40
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.
41
#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()
42
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.)
43
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.
44
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;
45
#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";
46
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.
47
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.
48
Syntax: class Base { public: virtual void funct()=0; };
49
#include <iostream> class shape { public: virtual void draw()=0; }; class Rectangle: public shape void draw(); class Circle: public shape
50
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.
51
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(::*)
52
Operators that Can and Cannot be Overloaded
Deitel & Deitel, Figure 22.1 Deitel & Deitel, Figure 22.2 Operator Overloading CS-2303, C-Term 2010
53
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
54
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.
55
Where a friend cannot be used = Assignment operator ()Function call operator [] Subscripting operator ->class member access operator
56
Student Book Types of Operator Unary operator Binary operator
57
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
58
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”;
59
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;
60
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)
61
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;
62
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(); }
63
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);
64
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();
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.