Inheritance
Introduction Reusability--building new components by utilizing existing components- is yet another important aspect of OO paradigm. It is always good/ “productive” if we are able to reuse something that is already exists rather than creating the same all over again. This is achieve by creating new classes, reusing the properties of existing classes. It saves money , time, efforts etc.
Definition This mechanism of deriving a new class from existing/old class is called “inheritance”. The old class is known as “base” class, “super” class or “parent” class. The new class is known as “sub” class, “derived” class, or “child” class. Example:
Defining Derived classes Syntax: class DerivedClassName : access-level BaseClassName where access-level specifies the type of derivation private by default, or Public Protected Any class can serve as a base class Thus a derived class can also be a base class
class derived_classname : <access-specifier>base_classname Implementing Inheritance in C++ by Deriving Classes From the Base Class Syntax: class base_classname { … }; class derived_classname : <access-specifier>base_classname ...
int main() { derived d; d.getdata(); d.display(); d.get(); d.disp(); #include<iostream> using namespace std; class base { int num1; public: int num2; void getdata() num1=10; num2=20; } void display() cout<<num1<<" "; cout<<num2<<endl; }; class derived:public base { int num3; public: void get() num2=30; num3=40; } void disp() cout<<num2<<" "; cout<<num3<<endl; }; int main() { derived d; d.getdata(); d.display(); d.get(); d.disp(); return 0; }
Types of Inheritance Single Inheritance Multiple Inheritance Hierarchical Inheritance Multilevel Inheritance Hybrid Inheritance
Types of Inheritance
Types of Inheritance
Examples class ABC : private XYZ //private derivation { Members of ABC }; class ABC : public XYZ //public derivation class ABC : protected XYZ //protected derivation class ABC : XYZ //private derivation by default
Public inheritance When a base class is publicly inherited, ‘public members’ of the base class become ‘public members’ of the derived class and therefore they are accessible to the objects of the derived class. Note: private members of the base class are not accessible in the derived class (to preserve encapsulation)
Private inheritance Public members of base class become private members of derived class Protected members of base class become private members of derived class Public and protected members are only available to derived-class member functions - not to a derived object. They are inaccessible to the objects of the derived class.
Protected inheritance A member declared as protected is accessible by the member functions within its class and any class immediately derived from it. It cannot be accessed by the functions outside these two classes. It is possible to inherit a base class in protected mode. In this, Public and protected members of the base class become protected members of the derived class.
int main() { B b1; b1.get(10); b1.put(); b1.sum(); return 0; } #include<iostream> using namespace std; class A { protected: int x; public: void getdata(int m) x=m; } void putdata() { cout<<x; }; class B:protected A { protected: int y; public: void get(int n) { y=n; getdata(8); } void put() cout<<y<<" "; putdata(); void sum() int z=x+y; cout<<"sum="<<z; } }; int main() { B b1; b1.get(10); b1.put(); b1.sum(); return 0; } PROG.OF SINGLE INHERITANCE IN PROTECTED MODE
Private: // visible to member function within class// Protected: // visible to member functions of its own and immediate derived class// Public: // visible to all functions in the program//
Not Inheritable Class B Private Protected Public ClassD2:private B Class D1:public B Private Protected Public Private Protected Public Class X:public D1,protected D2 Private Protected Public
Access Rights of Derived Classes Type of Inheritance Private inheritance Protected inheritance Public inheritance private Not inherited protected Private public Access Control for Members The type of inheritance defines the access level for the members of derived class that are inherited from the base class
Adding members “Publicly & Privately” Public Inheritance Private Inheritance
Multiple Inheritance Is the phenomenon where a class may inherit from two or more classes Syntax: class derived : public base1, public base2 { //Body of class }; Base classes are separated by comma M N P 20
Multiple Inheritance class P:public M, public N #include <iostream> Using namespace std; class M { protected: int m; public: void getm(int x) { m=x; } }; class N int n; Public: void getn(int y) { n= y;} class P:public M, public N { public: void display(); }; void P::display() { cout<<“m=“<<m<<“\n”; cout<<“n=“<<n<<“\n”; cout<<“m*n=”<<m*n<<“\n”; } int main() P p; p.getm(10); //m=10 p.getn(20); //n=20 p.display(); //m*n = 200 return 0; class P:public M, public N { public: void display(); }; void P::display() { cout<<“m=“<<m<<“\n”; cout<<“n=“<<n<<“\n”; cout<<“m*n=”<<m*n<<“\n”; } int main() P p; p.getm(10); //m=10 p.getn(20); //n=20 p.display(); //m*n = 200 return 0;
Multilevel Inheritance It is also possible to derive a class from an existing derived class. It is implemented by defining atleast three classes. Each derived class must have a kind of relationship with its immediate base class. A B C
Multilevel Inheritance #include <iostream> using namespace std; class student { protected: int rollno; public: void getno(int a) { rollno=a; } void putno() cout<<“Roll No. is”<<rollno; } }; class test : public student { protected: float sub1,sub2; public: void getmarks(float x, float y) { sub1=x; sub2=y; } void putmarks() { cout<<“Marks in sub1”<<sub1<<endl; cout<<“Marks in sub2”<<sub2<<endl; } }; class result:public test { float total ; public: void display() ; }; void result:: display() {total= sub1+sub2; putno();//func. of class student putmarks();/function of class test cout<<“total = “<<total; } int main() { result student1; student1.get_no(102); student1.get_marks(80.0,98.5); student1.display(); return 0;
Overriding and Overloading Parent Class Functions When any class member function is called, the following steps take place: The compiler looks for a matching function in the class of the object using the function name If no match is found in this class, the compiler looks for a matching function in the parent class If no match is found in the parent class, the compiler continues up the inheritance hierarchy, looking at the parent of the parent, until the base class is reached If no match is found in any class, an error message is issued
Ambiguity in Multiple Inheritance Can arise when two base classes contain a function of the same name Example: M N P
class P:public M,public N { public: void show() Ambiguity in Multiple Inheritance class M { public: void display() cout<<"in class M"; } }; class N cout<<"in class N"; class P:public M,public N { public: void show() cout<<"in class P"; } }; int main() P ob; ob.show(); ob.display(); return 0;
Can be resolved By overriding the function in the derived class int main() { P ob; ob.M::display(); ob.N::display(); return 0; }
Ambiguity in Single Inheritance class A { public: void display() cout<<“A\n”; } }; class B: public A cout<<“B\n”; int main() { B b; b.display(); return 0; } In this case, the function in the derived class overrides the inherited function.
Can be resolved: By using the scope resolution operator int main() { B b; b.A::display(); b.B::display(); }
Hybrid Inheritance Record Marks Avg Result
Virtual base class Student Test score result //Multiple copies of the variables of student class are generated
Virtual base class class A { ……. ……… }; class B1:virtual public A {……. ……. class B2:public virtual A …….. class C:public B1,public B2 {……… }; //only one copy of A will be inherited A B1 B2 C
Virtual base class class test : virtual public student class student { protected: int rollno; public: void getroll() cout<<"enter roll no"; cin>>rollno; } void putroll() cout<<rollno; }; class test : virtual public student { protected: int mark1,mark2; public: void getmarks() cout<<"enter the marks of subjects"; cin>>mark1>>mark2; } void putmarks() cout<<mark1<<mark2; };
class sports: public virtual student { protected : int score; public: void getscore() { cout<<"enter the marks in sports"; cin>>score; } void putscore() { cout<<score; } }; class result : public test , public sports int total; void sum(); }; void result::sum() { total=mark1+mark2+score; cout<<"rollno"<<rollno<<"\n"; cout<<"mark1"<<mark1<<"\n"; cout<<"mark2"<<mark2<<"\n"; cout<<“score is"<<score<<"\n"; cout<<"total is"<<total; } int main() result r1; r1.getroll(); r1.getmarks(); r1.getscore(); r1.sum();
Abstract Class An abstract class is one that is not used to create objects. An abstract class is designed only to act as a base class i.e. to be inherited by other classes. It is a design concept in program development and provides a base upon which other classes may be built. class sample { int x,y; public: virtual void show()=0; }
Constructors and Inheritance If a base class constructor takes no arguments, the derived class need not to have constructor function. If any base class contain constructor with one or more arguments, then it is mandatory for the derived class to have a constructor and pass the arguments to the base class constructor. When both the derived and base classes contain constructor, the base class constructor is executed first and then the constructor in the derived class is executed.
Order of Constructors and destructors in derived classes Derived-class constructor Calls the constructor for its base class first to initialize its base-class members If the derived-class constructor is omitted, its default constructor calls the base-class’ default constructor Destructors are called in the reverse order of constructor calls. Derived-class destructor is called before its base-class destructor
Constructors in Derived Class
The general form of defining a derived constructor is : Der_constructor(par_list) : base1(par_list1), base2(par_list2) { // implementation of derived class constructor } Here Der_constructor is the name of derived class constructor and par_list specifies the list of parameters that the derived class constructor will receive, out of which some may be used to initialize its own data members whereas remaining ones may be passed to its base class constructors. Initialization list starts with colon(:) and consists of calls to base class constructors where each call is separated by comma.
Example Derived class object created as: Definition of constructor called:
Order of Constructors in derived classes Class B:public A { //A() base constructor }; //B() derived constructor Class A:public B, public C { //B() base first }; //C() base second //A() derived Class A:public B, virtual C { //C() virtual base }; //B() ordinary base
Constructors in derived classes #include <iostream> class alpha { int x; public: alpha(int i) { x=i; cout<<“alpha initialized”; } void showx() { cout<<“x=“<<x;} }; class beta { float y; beta(float j) { y=j; cout<<“beta initialized”;} void showy() cout<<“y=“<<y; } class gamma:public beta, public alpha { int m,n; public: gamma(int a, float b,int c, int d) :alpha(a), beta(b) m=c; n=d; cout<<“gamma initialized”; } void showmn(void) cout<<“m=“<<m; cout<<“n=“<<n; }; int main() { gamma g(5,12.34,50,20); g.showx(); g.showy(); g.showmn(); return 0; } Output: beta initialized alpha initialized gamma initialized x=5 y=12.34 m=50 n=20
Aggregation Here object of one class is declared as member of another class class Date { private: int month, day, year; public: Date(int m, int d, int y) month = m; day = d; year= y; } }; class student { private: int id_no; Date dob; public: student(int id, int d, int m, int y) : dob(d,m,y) id_no = id; } }; Object of Date class Constructor is called
Object Slicing When a derived class object is assigned to a base class object. only base class data will be copied from derived class and derived data will be sliced. This will occur in C++.
When a Derived Class object is assigned to Base class, the base class' contents in the derived object are copied to the base class leaving behind the derived class specific contents. This is referred as Object Slicing. That is, the base class object can access only the base class members. This also implies the separation of base class members from derived class members has happened.
Object Slicing Base & Derived class Main() function class base { public: int i, j; }; class derived: public base int k; int main() { base b; derived d; b=d; } Derived class members are copies one-by-one into base class
Object Slicing (cont.) class base { public: int i; int j; }; class derived: public base { public: int i; int j; int k; }; copied Gets sliced. Means on copied to anything
Object slice prevention Object slicing can be prevented by making the base class pure virtual, so that base instance will not be allowed.(It is not possible to create the object of a class which contains a pure virtual method.) Object slicing can't occurr, if pointers or reference to the objects used, as both pointers of the same size.
class derived: public base {public: int b; derived() { b=20; a=30 } class base { public: int a; base() { a = 10; Cout<<a; } }; class derived: public base {public: int b; derived() { b=20; a=30 } int main() { base b; derive d; cout< < "size of base class is "< < sizeof(b)< < endl; cout< < "size of derive class is "< < sizeof(d)< < endl; b=d; cout< < "size of b class is "< < sizeof(b)< < endl; } Output: size of base class is 4 10 size of derive class is 8 10 size of b class is 4 30
Object Delegation It is behaviour of object in terms of another object. Alternative to class inheritance. Here, 2 objects are involved in handling request: A receiving object delegates operations to its delegate. It is analogous to child classes sending request to parent classes.
Example Constructor Function of class A called to perform task A class object declared Constructor Function of class A called to perform task Object of class A passed in constructor
Inheritance(egAggration concepts, The const keyword) Const argument- Int student(const section *s); Const member function- the functions wont change any value in the function. The compiler will generate the error if functions tries to alter the data. Void mul(int, int) const; //declaration Void mul(int a, int v) const //definition { ...; }
class ABC { public: int a; void func() a=99; } void confunc() const a=100; //error cant modify a member. }; int main() { ABC ob; ob.func(); cout<<ob.a; ob.confunc(); cout<<ob.a; return 0; }
Const object syntax const classname objectname; eg: Const student s1; Const object calls only const member functions.