430 likes | 590 Vues
Inheritance Basics. What is Inheritance?. Inheritance allows a new class to be based on an existing class. The new class inherits all the member variables and functions of the class it is based on . “ T he mechanism by which one class acquires the properties of another class”. Inheritance.
E N D
What is Inheritance? • Inheritance allows a new class to be based on an existing class. The new class inherits all the member variables and functions of the class it is based on. • “The mechanism by which one class acquires the properties of another class”
Inheritance This existing class is called the base class, and the new class is called the derived class. Other programming languages, such as Java and C#, refer to the base class as the superclass and the derived class as the subclass. A derived class represents a more specialized group of objects.
Reusability • Inheritance is an essential part of OOP, Its big role is that it permits code reusability. • Once a base class is written and debugged, it need not be touched again. • But, using inheritance, can nevertheless be adapted to work in different situations. Reusing existing code saves time and money and increases a program’s reliability
Relationship between classes • In object oriented programming there are two types of relationships between classes which are commonly used • Is-a relationship: • The is-a relationship represents inheritance. In an is-a relationship, an object of a derived class also can be treated as an object of its base class e.g, a Car is a Vehicle, so any attributes and behaviors of a Vehicle are also attributes and behaviors of a Car • Has-a relationship: • In a has-a relationship, an object contains one or more objects of other classes as members. e.g, a Car has many components—it has a steering wheel, has a brake pedal, has a transmission, etc
Arrange concepts into an inheritance hierarchy • Concepts at higher levels are more general • Concepts at lower levels are more specific (inherit properties of concepts at higher levels) Vehicle Wheeled vehicle Boat Car Bicycle 2-door 4-door
Protected Members Use in Derived Class • Protected members of a base class are like private members, but they may be accessed by derived classes. The base class access specification determines how private, protected, and public base class members may be accessed by derived classes.
Inheritance Subgroupings with respect to a parent are called • Subclass • Derived Class • Children The derived class • inherits from the parent all • characteristics • properties • capabilities • can modify or extend inherited abilities
Inheritance • Study the vehicle hierarchy: • Note that each entity is also a class • Classes are used in an object centered paradigm as a means of encapsulating common data and functions shared by members of the class VEHICLE LANDBASED AUTOMOBILE BICYCLE
Vehicle WaterBased LandBased MotorBoat Automobile AutoBoat Types of Inheritance according to Number of base classes Single Inheritance Each class or instance object has a single parent Multiple Inheritance Classes inherit from multiple base classes ( might not have same ancestors as shown in the example below) Defines a relationship Between several (independent) class types Example: Multiple Parents Common Ancestor
Types of Inheritance According to Accessibility • A class(Derived Class) can be derived from another class(Base Class) by using access specifiers Private, Protected and Public with the name of base class. On the bases of using these access specifiers inheritance is divided into three types • Private Inheritance • Protected Inheritance • Public Inheritance
Private inheritance • In this type of inheritance access specifiers private is used with the name of base class during declaration of derived class e.g. • class child : private parent
Protected inheritance • In this type of inheritance access specifiers protected is used with the name of base class during declaration of derived class e.g. • Class child : protected parent
Public inheritance • Public inheritance using public access specifier with the name of the base class during the declaration of derived classes. • class child : public parent • A base class’s private members are accessible only within its body and to the friends of that base class. In this section, we introduce the access specifier protected. • Using protected access offers an intermediate level of protection between public and private access. A base class’s protected members can be accessed within the body of that base class, by members and friends of that base class, and by members and friends of any classes derived from that base class
Inherited Member Initialization • Initialized in two ways: • If the base class has only a default constructor=> initialize the member values in the body of the derived class constructor • If the base class has a constructor with arguments=> the initialization list is used to pass arguments to the base class constructors syntax (for Single Base Class) DerivedClass ( derivedClassargs ) : BaseClass ( baseClassargs ) { DerivedClass constructor body } • The set of derived class constructor arguments may contain initialization values for the base class arguments
e.g.1 #include<iostream.h> #include<conio.h> using namespace std; class A { Private: int data; A() { Data=0; } public: intget_data(intarg) { data = arg; return data; } Void put_data() { Cout<<“ data =“<<data; } } };
class B : public A { }; void main() { B obj; Int a; Cout<<“Enter value”<<endl; Cin>>a; obj.get_data(a); cout << obj.put_data() << endl; getch() }
e.g; 2 #include <iostream.h> using namespace std; // Base class class Shape { protected: int width; int height; public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } };
(Cont) // Derived class class Rectangle: public Shape { public: intgetArea() { return (width * height); } }; void main(void) { Rectangle Rect; Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object cout << "Total area: " << Rect.getArea() << endl; return 0; }
Assignment #3 • Q1. Write a program to implement the inheritance process of following defined classes. • A base class named calculate which have data members a, b, c, d, e and %age using a member function of the derived class. • Find the percentage of the five subjects marks. Using base and derived classes. • Q2. write a program to implement the inheritance process of following defined classes • A base class named as shape • A derived class named triangle. Data members and member functions must not b defined in both classes. • Find the area of triangle by using the derived classes. Submission Date: 14/7/2014.
Overriding of Member Functions • We can use member functions of the base classes in the derived classes. • These functions have the same name in the derived classes as those in the base classes. • The call of these are in the programs in the same way for objects of both base and derived classes.
e.g; #include <iostream> using namespace std; #include <process.h> //for exit() class Stack{ protected: intst[3]; inttop; public: Stack() { top = -1; } void push(intvar) { st[++top] = var; } int pop() { return st[top--]; }};
class Stack2 : public Stack { public: void push(intvar) { if(top >=3-1) { cout << “\nError: stack is full”; exit(1); } Stack::push(var); } int pop() { if(top < 0) { cout << “\nError: stack is empty\n”; exit(1); } return Stack::pop(); } };
int main() { Stack2 s1; s1.push(11); s1.push(22); s1.push(33); cout << endl << s1.pop(); cout<< endl << s1.pop(); cout << endl << s1.pop(); cout << endl << s1.pop(); cout << endl; return 0; }
Levels of inheritance • Classes can be derived from classes that are themselves derived. • Here’s a mini program syntax shows the basic idea class A { }; class B : public A { }; class C : public B { }; • Here B is derived from A, and C is derived from B.
As a more concrete example, suppose that we decided to add a special kind of laborer called a foreman to the EMPLOY program
Multiple Inheritance • Multiple inheritance represents derivation of a class from more than one base classes. • In multiple inheritance object of derived class can accessed the PROTECTED and PUBLIC member of all its base classes. • Let parent1 and parent2 are two base classes of derived class
Multiple Inheritance Syntax • Derived class : public class1, public class2 e.g; class child : public parent1, public parent2
Multiple Inheritance example #include<iostream> class parent1{ protected: int x; public: void input1(int a) { x=a; } };
Class parent2 { protected: int y; public: void input2(int a) { y=a; } };
class child : public parent1, public parent2 { public: void input(int x, int y) { parent1::input1(x); parent2::input2(x); } void display() { cout<<“value of x= “<<x << endl; cout<<“value of y= “<<y<<endl; } };
void main() { child obj; obj.input(40,50) obj.display(); }
Friend Function • Private data member of a class can not be accessed by an object of another class • Similarly protected data member function of a class can not be accessed by any other class except its derived classes • The purpose of the friend function is to bring the objects of different classes on same platform and access its private and protected data members.
Friend Function • Following points must be noted for the use of a friend function • Friend function must be defined outside of all classes for which friend function is declared or not • The prototype of friend function must be define in each class within scope of any access-specifier • The reserve word friend must be only preceded by the prototype of friend function not the definition part of friend function • The arguments of friend function may be of class type • Friend function can return data of any primitive type but sometime you can use void
Friend Function • Use of friend function can enhance performance.
Example #include "stdafx.h" #include "iostream" class number2; class number1 { private: int x; public: number1(){ x=5; } friend int sum(number1,number2); };
class number2 { private: int y; public: number2(){ y=20; } friend int sum(number1,number2); };
int sum(number1 ob1,number2 ob2) { return ob1.x+ob2.y; } int _tmain(intargc, _TCHAR* argv[]) { number1 obj1; number2 obj2; std::cout<<"Sum of private data member "<<sum(obj1,obj2)<<std::endl; system("PAUSE"); return 0; }
Example 2 #include "stdafx.h" #include <iostream> using namespace std; class count { private: intx; public: count() : x( 0 ) { } void print() const { cout << x << endl; } friend void setX(count &c, intval); };
Example 2 void setX(count &c, intval) { c.x=val; } int _tmain(intargc, _TCHAR* argv[]) { count obj; cout<<"counter.x after instantiation: "; obj.print(); setX(obj, 8); cout<<"counter.x after call to setX friend function: "; obj.print(); system("PAUSE"); return 0; }