Sei sulla pagina 1di 90

Inheritance

Inheritance
• Mechanism of deriving new classes from existing
classes.
Class that is inherited,
Existing Class
known as a base class

Class that does the inheritance,


New Class
known as the derived class
• Members of base class become members of the
derived class.
Thapar University UTA007 - Computer Programming I 2
Contd…
• Syntax:
class derivedClassName : access-specifier baseClassName
{ // Body of the derived class };

• access-specifier
– Decides status of base class members in the
derived class.
– Can be public, private, or protected.
– Is private by default.
Thapar University UTA007 - Computer Programming I 3
Base Class – Access Control
• In any case, the private members of the base class
– Remain private to the base class only.
– Are not accessible by the members of the
derived class. Access-specifier
Base class member Accessibility in the derived class
accessibility
private protected public
Public Private Protected Public
Protected Private Protected Protected

Thapar University UTA007 - Computer Programming I 4


• Inheritance is one of the key features of
Object-oriented programming in C++. It allows
user to create a new class (derived class) from
an existing class(base class).
• The derived class inherits all the features from
the base class and can have additional
features of its own.
Why inheritance should be used?

• Suppose, in your game, you want three


characters - a maths teacher, a footballer and
a businessman.
• Since, all of the characters are persons, they can
walk and talk. However, they also have some
special skills. A maths teacher can teach maths, a
footballer can play football and a businessman
can run a business.
• You can individually create three classes who can
walk, talk and perform their special skill as shown
in the figure below.
In each of the classes, you would be copying the same code for walk and talk
for each character.

If you want to add a new feature - eat, you need to implement the same
code for each character. This can easily become error prone (when
copying) and duplicate codes.
• it'd be a lot easier if we had a Person class with basic features like talk,
walk, eat, sleep, and add special skills to those features as per our
characters. This is done using inheritance.
• This makes your code cleaner, understandable and extendable.
• When working with inheritance, each derived class should satisfy the
condition whether it "is a" base class or not. In the example above, Maths
teacher is a Person, Footballer is a Person
class Person
{ ... .. ...
};
class MathsTeacher : public Person
{ ... .. ...
};
class Footballer : public Person
{ .... .. ...
};
What is inheritance?
• Inheritance allows software developers to derive a new
class from the existing class. The derived class inherits
features of the base class (existing class).
• The language mechanism by which one class acquires
the properties (data and operations) of another class
Geometric Figure

Two Dimensional Three Dimensional

• Base Class (or superclass): the class being inherited


from (Geometric Figure)
• Derived Class (or subclass): the class that inherits
(Three Dimensional), (Two Dimensional)
Advantages of inheritance

• When a class inherits from another class,


there are three benefits:
• (1) You can reuse the methods and data of
the existing class
(2) You can extend the existing class by
adding new data and new methods
(3) You can modify the existing class by
overloading its methods with your own
implementations
Contd…
• Syntax:
class derivedClassName : access-specifier baseClassName
{ // Body of the derived class };

• access-specifier
– Decides status of base class members in the
derived class.
– Can be public, private, or protected.
– Is private by default.
1
Thapar University UTA007 - Computer Programming I
3
Inheritance and accessibility
• A derived class inherits the behavior of
base class and enhances it in some way
• Inheritance does not mean inheriting
access to another class private members
What a derived class inherits
• Every data member defined in the parent class
(although such members may not always be
accessible in the derived class!)
• Every ordinary member function of the parent class
(although such members may not always be
accessible in the derived class!)
Class Derivation
Any class can serve as a base class…
– Thus a derived class can also be a base class
syntax
class DerivedClassName:mode BaseClassName
DerivedClassName - the class being derived
mode - mode of inheritance specifies
access to the base class
members, whether
public,
protected or
private
- private by default
Types of inheritance

Inheritance

Single Multi-level Multiple Hierarchical Hybrid


Inheritance Inheritance Inheritance Inheritance Inheritance
Single Inheritance
• Derived class inherits from only one base class
Company (Base class)

(Derived class)
Employee
class Company { …
}
class Employee : public Company {…
}
Multi-level Inheritance
• Derived class inherits from a class that itself inherits
from another class
Student

Test

Result
class Student:{…}
class Test: public Student{…}
class Result: public Test {…}
Multiple Inheritance
• Derived class inherits from more than one
base class
Person Company

Employee
class Person:{…}
class Company:{…}
class Employee: public Person, public Company
{…}
Hierarchical Inheritance
• Base class is inherited by more than one derived
classes
Student

Arts Engineering Medical

class Student:{…}
class Arts : public Student{…}
class Engineering: public Student{…}
class Medical : public Medical {…}
Hybrid Inheritance
• Combination of above three types inheritance is hybrid
inheritance

Student

Test Sports

Result

class Student:{…}
class Test: public Student{…}
class Sports: {…}
class Result: public Test, public Sports {…}
Hybrid Inheritance
• Hybrid: Applying two or more types of inheritance.
class A class B
class A
Multiple
Single
class C
class B
Hierarchical
class D
class C class D Multi – level

Thapar University UTA007 - Computer Programming I


class E 23
Modes of inheritance
• Three modes of inheritance
– public
– private (mode by default)
– protected
• Accessibility or visibility of base class
members (variables and functions) in derived
class depends upon the mode of inheritance.
Base Class – Access Control
• In any case, the private members of the base class
– Remain private to the base class only.
– Are not accessible by the members of the
derived class. Access-specifier
Base class member Accessibility in the derived class
accessibility
private protected public
Public Private Protected Public
Protected Private Protected Protected
2
Thapar University UTA007 - Computer Programming I
5
Public Mode/Derivation
• The public keyword in the inheritance syntax
means that publicly accessible members
inherited from the base class stay publicly
accessible in the derived class
Base Class Derived Class

Private member Not inherited

Public member Public


Protected member Protected
Private Mode/Derivation
• Public 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.
Base Class Derived Class

Private member Not inherited

Public member Private


Protected member Private
Protected Mode/Derivation
• Private members of the base class are not accessible in
the derived class (to preserve encapsulation)
• Protected qualification, thus allows encapsulated data
members which are not publicly accessible to be
accessible by derived classes
• Protected members are not accessible from outside
the class, except in derived classes
Base Class Derived Class

Private member Not inherited

Public member Protected

Protected member Protected


Inheritance and protected Members
• Protected members of a class are similar to private
because,
– Can be accessed by members of a class.
– Not accessible by non-members of a class.

• But, dissimilar to private members


– During inheritance, protected members can be
inherited and accessed by the derived.
2
Thapar University UTA007 - Computer Programming I
9
class base
{ public: int x;
protected: int y;
private: int z; };
class publicDerived: public base {
// x is public
// y is protected
// z is not accessible from publicDerived
};
class protectedDerived: protected base
{ // x is protected
// y is protected
// z is not accessible from protectedDerived
};
class privateDerived: private base
{ // x is private
// y is private
// z is not accessible from privateDerived
};
Example – 3
1. #include<iostream> 12. class derived : public base
2. using namespace std; 13.{ int k;
3. class base 14. public:
4. { protected: 15.void setk()
16. { k = i * j; }
5. int i, j;
17. void showk()
6. public: 18. { cout << " " << k; }
7. void set(int a, int b) 19. };
8. { i = a; j = b; } 20. int main()
9. void show() 21. { derived ob; ob.set(2,3);
10. { cout << i << " " << j; } 22. ob.show();
11. }; 23. ob.setk(); ob.showk();
Output 2 3 6
24. return 0; } 3
Thapar University UTA007 - Computer Programming I
1
Example – 4
1. #include<iostream> 12. class derived : protected base
13. { int k;
2. using namespace std;
3. class base 14. public:
4. { protected: 15. derived (int a, int b, int c)
5. int i, j; • 16. { set(a, b); k = i * j; }
6. public: • 17. void showk()
7. void set(int a, int b) 18. { show();
8. { i = a; j = b; } 19. cout << " " << k; }
9. void show() 20. };
21. int main()
10. { cout << i << " " << j; }
11. }; 22. { derived ob(2,3);
23. ob.showk();
Output 2 3 6
24. return 0; } 3
Thapar University UTA007 - Computer Programming I
2
If access-specifier is private, then the
1
following program will not even compile.

1.#include<iostream> 12. class derived : public base


2. using namespace std; 13.{ int k;
3.class base 14. public:
4. { int i, j; 15.derived (int c)
16. { k = c; }
5. public:
17. void showk()
6. void set(int a, int b) 18. { cout << " " << k; }
7. { i = a; j = b; } 19. };
8. void show() 20. int main()
9. { cout << i << " " << j; } 21. { derived ob(3); ob.set(1,2);
10. }; Output 22. ob.show(); ob.showk();
23. return 0;
123 24. } 3
Thapar University UTA007 - Computer Programming I
3
Example – 2 (Inheriting Privately)
1.#include<iostream> 12. class derived : private base
2. using namespace std; 13. { int k;
3.class base 14. public:
4. { int i, j; 15. derived (int a, int b, int c)
16. { set(a, b); k = c; }
5. public:
17. void showk()
6. void set(int a, int b) 18. { show();
7. { i = a; j = b; } 19. cout << " " << k; }
8. void show() 20. };
9. { cout << i << " " << j; } 21. int main()
10. }; Output 22. { derived ob(1,2,3);
23. ob.showk();
123
24. return 0; } 3
Thapar University UTA007 - Computer Programming I
4
Example
class student public:
{ void get_marks(float,float);
protected: void put_marks();
int roll_number; }; //ending test class
public: void test:: get_marks(float x,float y)
void get_number(int); {
void put_number(); sub1 = x;
}; sub2 = y;
void student::get_number(int a) }
{ void test::put_marks()
roll_number = a; {
} cout<<“Marks in first subject”<< sub1;
void student::put_number() cout<<“Marks in second subject”<< sub2;
{ }
cout<<“Roll number is”<<roll_number; class result: public test
} {
class test : public student float total;
{ public:
protected: void display();
float sub1; };
float sub2; void result:: display()
{
cout<<“Total marks”<<sub1 + sub2; }
Example
• Instance of class result will have
– private:
• float total; //own member
– protected:
• int roll_number; //inherited from student via test
• float sub1; //inherited from test
• float sub2; //inherited from test
– public:
• void get_number(int); //from student via test
• void put_number(); //from student via test
• void get_marks(float,float); //from test
• void put_marks(); //from test
• void display() //own member
Single Inheritance
class Cube: public Value
#include <iostream>
{
using namespace std; public:
int cube()
{
class Value return (val*val*val);
}
{ };
protected:
int main ()
int val; {
Cube cub;
public: cub.set_values (5);
void set_values (int a) cout << "The Cube of 5 is=" << cub.cube() <<
endl;
{ return 0;
}
val=a;
}
};
Hierarchical Inheritance
#include <iostream> class Cube:public Side
using namespace std; {
class Side public:
{ int cub()
protected: { return (l *l*l); }
int l; };
public: int main ()
void set_values (int x) {
{ l=x;} Square s;
}; s.set_values (10);
class Square: public Side cout << "The square value is::" << s.sq() << endl;
{ Cube c;
public: c.set_values (20);
int sq() cout << "The cube value is::" << c.cub() << endl;
{ return (l *l); } return 0;
}; }
Accesibility in inheritance(yes/no)
A Private x, public y protected z A Private x, public y protected z

Public inheritance Private inheritance

B Not inherited x ,public y ,protected z


B Not inherited x private y private z

Public inheritance Private inheritance

C Not inherited x, public y ,protected z C Not inherited x,y,z


Accesibility in inheritance(yes/no)
A Private x, public y protected z

Protected inheritance

B Not inherited x ,protected y ,protected z

Protected inheritance

C Not inherited x ,protected y ,protected z


Multilevel Inheritance
#include <iostream> class C : public B
using namespace std; {
public:
class A void view()
{ {
public: cout<<"Derived2 class content."<<endl;
void display() }
{
cout<<"Base class content."<<endl; };
}
}; int main()
{
class B : public A C c;
{ c.show();
public: c.view();
void show() c.display();
{ return 0;
cout<<"Derived1 class content."<<endl; }
}
};
#include <iostream>
using namespace std;
class Mammal
{ public:
Mammal() { cout << "Mammals can give direct birth." << endl;
}
};
class WingedAnimal
{ public: WingedAnimal()
{ cout << "Winged animal can flap." << endl; }
};
class Bat: public Mammal, public WingedAnimal
{ };
int main() { Bat b1; return 0; }
Multiple Inheritance
#include<iostream>
using namespace std; class statement:public student,public sports
class student {
int tot,avg;
{ protected:
public:
int rno,m1,m2;
void display()
public: {
void get() tot=(m1+m2+sm);
{ cout<<"Enter the Roll no :"; avg=tot/3;
cin>>rno; cout<<"\n\n\tRoll No :
cout<<"Enter the two marks :";
"<<rno<<"\n\tTotal : "<<tot;
cout<<"\n\tAverage : "<<avg;
cin>>m1>>m2; }
}
}; };
class sports int main()
{ protected: { statement obj;
int sm; // sm = Sports mark obj.get();
public: void getsm() obj.getsm();
{ obj.display();
cout<<"\nEnter the sports mark :"; }
cin>>sm;
}};
Constructor and Inheritance
• Base class constructors are always called in the
derived class constructors.
• Whenever you create derived class object, first the
base class default constructor is executed and then
the derived class's constructor finishes execution.
• Whether derived class's default constructor is called
or parameterized is called, base class's default
constructor is always called inside them.
• To call base class's parameterized constructor inside
derived class's parameterized constructor, we must
mention it explicitly while declaring derived class's
parameterized constructor.
Constructors in inheritance
• Derived class need not have parameterized constructor
if base class does not have any.
• If any of the inherited base classes has a parameterized
constructor then derived class must have a
parameterized constructor.
– So that the derived class constructor passes values to base
class constructor
• For multiple inheritance, constructors are called in the
order in which base classes appear in declaration of
derived class
• For multilevel inheritance, constructors are called in
the order of inheritance
Example
Method of inheritance Order of execution
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 B:public A { A(); base(first-level)


}; B(); base(second-level)
class C:public B {}; C(); derived
Base class Default Constructor in
Derived class Constructors
class Base int main()
{ int x; {
public: Base b;
Base() { cout << "Base default Derived d1;
constructor"<<endl; } Derived d2(10);
}; }
class Derived : public Base
{ int y;
OUTPUT
public:
Base default constructor
Derived() { cout << "Derived default Base default constructor
constructor"<<endl; }
Derived default constructor
Derived(int i) { cout << "Derived Base default constructor
parameterized
constructor"<<endl; } Derived parameterized constructor
};
Parameterized Base-Class
Constructors
•How to pass arguments to
a constructor in a base
class?
Solution
• Use expanded form of derived class constructor
declaration.
derived(argList):base1(argList), base2(argList)…
{ // Body of derived class constructor.
}
• If any of the inherited base classes have a
parameterized constructor then derived class must
have a parameterized constructor to pass values to
the base class constructor.
Thapar University UTA007 - Computer Programming I 28
Example – 1Constructing
(Single)base
Constructing derived
1. #include<iostream> Output 4 3
2. using namespace std; Destructing derived
3. class base
4. { protected: int i;
Destructing base
5. public: base(int x) { i = x; cout << "Constructing base\n"; }
6. ~base() { cout << "Destructing base\n"; } };
7. class derived : public base
8. { int j;
9. public: derived(int x, int y) : base(y)
10. { j = x; cout << "Constructing derived\n"; }
11. ~derived() { cout << "Destructing derived\n"; }
12. void show() { cout << i << " " << j << "\n"; } };
13. int main()
14. Thapar
{ derived
University
ob(3,4); ob.show(); return 0; }
UTA007 - Computer Programming I 29
Example – 2 (Multiple)
1. #include<iostream>
2. using namespace std;
3. class base1
4. { protected: int i;
5. public:
6. base1(int x) { i = x; cout << "Constructing base1\n"; }
7. ~base1() { cout << "Destructing base1\n"; } };
8. class base2
9. { protected: int k;
10. public:
11. base2(int x) { k = x; cout << "Constructing base2\n"; }
12. ~base2() { cout << "Destructing base2\n"; } };
Thapar University UTA007 - Computer Programming I 30
Contd… Constructing base1
Output Constructing base2
Constructing derived
435
13. class derived : public base1, public base2 Destructing derived
14.{ int j; Destructing base2
15.public: Destructing base1
16. derived(int x, int y, int z) : base1(y), base2(z)
17. { j = x; cout << "Constructing derived\n"; }
18. ~derived() { cout << "Destructing derived\n"; }
19. void show() { cout << i << " " << j << " " << k << "\n"; }
};
20. int main()
21. { derived ob(3,4,5); ob.show(); return 0; }
Thapar University UTA007 - Computer Programming I 31
Example – 3 (Parameterized Constructor in Base)
1. #include<iostream>
2. using namespace std;
3. class base1
4. { protected: int i;
5. public:
6. base1(int x) { i = x; cout << "Constructing base1\n"; }
7. ~base1() { cout << "Destructing base1\n"; } };
8. class base2
9. { protected: int k;
10. public:
11. base2(int x) { k = x; cout << "Constructing base2\n"; }
12. ~base2() { cout << "Destructing base2\n"; } };
Thapar University UTA007 - Computer Programming I 32
Constructing base1
Contd… Constructing base2
Constructing derived
Output 3 4
Destructing derived
Destructing base2
Destructing base1
13.class derived : public base1, public base2
14. { public:
15. derived(int x, int y) : base1(x), base2(y)
16. { cout << "Constructing derived\n"; }
17.~derived() { cout << "Destructing derived\n"; }
18. void show() { cout << i << " " << k << "\n"; } };
19. int main()
20. { derived ob(3,4); ob.show(); return 0; }
Thapar University UTA007 - Computer Programming I 33
Output???
1. #include<iostream>
2. using namespace std;
3. class base Output
4. { public: int i;
5. void display() { cout << i * i; } }; 400100
6. class derived : public base
7. { public: int j;
8. void display() { cout << j * j; }};
9. int main()
10. { derived ob;
11. ob.i = 10;
12. ob.j = 20;
13. ob.display(); ob.base::display();
14. Thaparreturn
University
0; } UTA007 - Computer Programming I 34
Output???
1. #include<iostream>
2. using namespace std; Error
3. class base { public: int i;};
4. class derived1 : public base { public: int j;};
5. class derived2 : public base { public: int k;};
6. class derived3 : public derived1, public derived2
7. { public: int sum; }; Classes Public
8. int main()
9. { derived3 ob; base i
10. ob.i = 10; ob.j = 20; ob.k = 30; derived1 i, j
11. ob.sum = ob.i + ob.j + ob.k; derived2 i, k
12. cout << ob.i << " " << ob.j << " "; derived3 i, j, i, k, sum
13. cout << ob.k << " " << ob.sum;
14.Thaparreturn
University
0; } UTA007 - Computer Programming I 35
3. class base 12. class derived : public base
4. { protected: int i, j; 13. { int k;
14. public: void setk() { k = i * j; }
5. public: 15. void showk() { cout << " " << k; }
6. void set(int a, int b) 16. };
7. { i = a; j = b; } 17. class derived1 : public derived
8. void show() 18. { int m;
9. { cout << i << " " << j; 19. public: void setm() { m = i – j; }
20. void showm() { cout << " " << m; }
10. } 21. };
11. };
Classes Public Protected Private
base set(), show() i, j -
derived set(), show(), setk(), showk() i, j k
derived1 set(), show(), setk(), i, j m
showk(), setm(), showm()
Thapar University UTA007 - Computer Programming I 59
Example – Contd…
22. int main()
Output
23. {
24. derived ob; derived1 ob1; 236
25. ob.set(2,3); ob.show(); 3 6 18 -3
ob.showk();
26. ob.setk();
27. cout << endl;
28. ob1.set(3,6); ob1.show();
29. ob1.setk(); ob1.setm();
30. ob1.showk(); ob1.showm();
31. return 0;
32. }
Thapar University UTA007 - Computer Programming I 60
3. class base 12. class derived : private base
4. { protected: int i, j; 13. { int k;
14. public: void setk() { k = i * j; }
5. public: 15. void showk() { cout << " " << k; }
6. void set(int a, int b) 16. };
7. { i = a; j = b; } 17. class derived1 : public derived
8. void show() 18. { int m;
{ cout << i << " " << j; 19. public: void setm() { m = i – j; }
9. 20. void showm() { cout << " " << m; }
10. } 21. };
11. };
This code will generate an error.
Classes Public Protected Private
base set(), show() i, j -
derived setk(), showk() - i, j, set(), show(), k
derived1 setk(), showk(),
- m
setm(), showm()
Thapar University UTA007 - Computer Programming I 61
3. class base 12. class derived : protected base
Contd…
4. { protected: int i, j; 13. { int k;
14. public: void setk() { k = i * j; }
5. public: 15. void showk() { cout << " " << k; }
6. void set(int a, int b) 16. };
7. { i = a; j = b; } 17. class derived1 : public derived
8. void show() 18. { int m;
{ cout << i << " " << j; 19. public: void setm() { m = i – j; }
9. 20. void showm() { cout << " " << m; }
10. } 21. };
11. };
Code in main() will generate an error – Slide 13.
Classes Public Protected Private
base set(), show() i, j -
derived setk(), showk() i, j, set(), show() k
derived1 setk(), showk(),
setm(), showm() i, j, set(), show() m
Thapar University UTA007 - Computer Programming I 62
Example
12. int main()
1. #include<iostream> 13.{ derived ob(20,30);
2. using namespace std; 14. ob.showx();
3. class base1 15.ob.showy();
4. { protected: int x; 16. return 0; }
5. public: void showx() { cout << x << " "; } };
6. class base2 Output
7. { protected: int y; 20 30
8. public: void showy() { cout << y << " "; } };
9. class derived : public base1, public base2
10. { int k;
11. public: derived(int a, int b) { x = a; y = b; } };
Thapar University UTA007 - Computer Programming I 63
Virtual Base Class
• Prevents the presence of multiple copies of the
members of the base class.
class base

class derived1 class derived2

class derived3
Thapar University UTA007 - Computer Programming I 36
Solution – Virtual Base Class
1. #include<iostream> Output
2. using namespace std; 10 20 30 60
3. class base { public: int i;};
4. class derived1 : virtual public base { public: int j;};
5. class derived2 : public virtual base { public: int k;};
6. class derived3 : public derived1, public derived2
7. { public: int sum; };
8. int main()
9. { derived3 ob;
10. ob.i = 10; ob.j = 20; ob.k = 30;
11. ob.sum = ob.i + ob.j + ob.k;
12. cout << ob.i << " " << ob.j << " ";
13. cout << ob.k << " " << ob.sum;
14.Thaparreturn
University
0; } UTA007 - Computer Programming I 37
Example – 1
****************************************************
Shape Angles Sides Dimensions Perimeter Area
****************************************************
Rectangle: 4 4 10.5, 5.2 31.4 54.6
Square: 4 4 4.5 18 20.25
Ellipse: 0 0 6.5, 3.2 32.1724 65.312
Circle: 0 0 2.5 15.7 19.625
Triangle: 3 3 6.3, 2.8, 3.8 12.9 3.0591
Triangle: 3 3 5.2, 1.9 7.1 4.94
****************************************************

Thapar University UTA007 - Computer Programming I 38


Contd…
Shape

Triangle Rectangle Ellipse

Square Circle

Thapar University UTA007 - Computer Programming I 39


shape
- name : char[]
- noOfAngles : int
ellipse triangle
- noOfSides : int
- major : float - side1 : float
+ shape(const char
- minor : float - side2 : float
*, int, int)
- side3 : float
+ getName() : char* + ellipse(const char *, float, float)
+ getAngles() : int + getMajor() : float + triangle(const char *, int,
+ getSides() : int + getMinor() : float int, float, float, float)
+ area() : float + triangle(const char *, int,
+ perimeter() : float int, float, float)
+ getBase() : float
+ getHeight() : float
rectangle + getThirdSide() : float
- length : float + area() : float
- breadth : float + perimeter() : float
+ rectangle(const char *, int, int, float, float) circle
+ getLength() : float
+ getBreadth() : float + circle(const char *, float)
+ area() : float square
+ perimeter() : float
+ square(const char *, int, int, float)
Thapar University UTA007 - Computer Programming I 40
Contd…
• rectangle r("Rectangle", 4, 4, 10.5, 5.2);
• • square s("Square", 4, 4, 4.5);
getName();
• • ellipse e("Ellipse", 6.5, 3.2);getAngles();
getSides();
• • circle c("Circle",2.5);
• triangle t1("Triangle", 3, 3, 6.3, 2.8, 3.8); perimeter();
• triangle t2("Triangle", 3, 3, 5.2, 1.9); area();
r.getLength(); r.getBreadth();
c.getMajor(); c.getMinor();
t1.getBase(); t1.getHeight(); t1.getThirdSide();
Thapar University UTA007 - Computer Programming I 41
Base class Parameterized Constructor
in Derived class Constructor
int main()
class Base
{
{public:
Derived d(10) ;
int x;
cout << d.x ; // Output will be 10
Base(int i)
{ x = i;
cout << d.y ; // Output will be 10
cout << "Base Parameterized Constructor"<<endl;
}
}
};

class Derived : public Base


{public: • OUTPUT
int y;
Derived(int j) : Base(j) Base Parameterized Constructor
{ y = j; Derived Parameterized Constructor
cout << "Derived Parameterized
Constructor"<<endlx; 10
} 10
};
Constructor in Multiple Inheritance
class B1
{public: class D:public B1,public B2
B1() {public:
{cout<<"Base 1 Default D()
constructor"<<endl; {cout<<"Derived Default
} constructor"<<endl;
}; }
};
class B2
{public: int main()
B2() {D d1;
{cout<<"Base 2 Default return 0;
constructor"<<endl; }
}
}; OUTPUT
Base 1 default constructor
Base 2 default constructor
Derived default constructor
#include<iostream>
using namespace std;
class Base1 {
public:
Base1()
{ cout << " Base1's constructor called" << endl; } When a class inherits from multiple classes,
}; constructors of base classes are called in the
class Base2 {
same order as they are specified in
inheritance.
public:
Base2()
{ cout << "Base2's constructor called" << endl; }
};
class Derived: public Base1, public Base2 {
public:
Base1′s constructor called
Derived() Base2′s constructor called
{ cout << "Derived's constructor called" << endl; } Derived’s constructor called
};

int main()
{ Derived d;
return 0;
}
Constructor in Multi level Inheritance
class B class D2:public D1
{public: {public:
B() D2()
{cout<<"Base Default {cout<<"Derived 2 Default
constructor"<<endl; constructor"<<endl;
} }
}; };
int main()
class D1:public B {
{public: D2 ob2;
D1() return 0;
{cout<<"Derived 1 Default }
constructor"<<endl;
} OUTPUT
}; Base default constructor
Derived 1 default constructor
Derived 2 default constructor
Destructors in inheritance
• Destructors are called in reverse order as that of constructors
class A:public B, public C
{
};

Order of execution of constructors and destructors:

B(); base(first) //B’s constructor


C(); base(second) //C’s constructor
A(); derived //A’s constructor
~A(); //A’s destructor
~C(); //C’s destructor
~B(); //B’s destructor
Example
class Base
{ public:
Base ( )
{ cout << "Inside Base constructor" << endl; } OUTPUT
~Base ( ) Inside Base constructor
{ cout << "Inside Base destructor" << endl;} Inside Derived constructor
}; Inside Derived destructor
class Derived : public Base Inside Base destructor
{ public:
Derived ( )
{ cout << "Inside Derived constructor" << endl;}
~Derived ( )
{ cout << "Inside Derived destructor" << endl; }
};
int main( )
{
Derived x;
}
C++ Function Overriding
• Suppose, both base class and derived class have a
member function with same name and
arguments (number and type of arguments).
• If you create an object of the derived class and
call the member function which exists in both
classes (base and derived), the member function
of the derived class is invoked and the function of
the base class is ignored.
• This feature in C++ is known as function
overriding.
C++ Function Overriding
• How to access the overridden function in the
base class from the derived class?
• To access the overridden function of the base
class from the derived class, scope resolution
operator :: is used. For example,
• If a derived class writes its own method, then all functions of base class with same name become
hidden, even if signaures of base class functions are different. In the above question, when fun() is
rewritten in Derived, it hides both fun() and fun(int) of base class.
#include<iostream>
using namespace std;

class Base
{
public:
int fun() { cout << "Base::fun() called"; }
int fun(int i) { cout << "Base::fun(int i) called"; }
};

class Derived: public Base


{
public:
int fun() { cout << "Derived::fun() called"; }
};

int main()
{
Derived d;
d.fun(5); //Compiler Error
return 0;
}
Ambiguity in Multiple Inheritance
• Suppose, two base classes have a same
function which is not overridden in derived
class.
• If you try to call the function using the object
of the derived class, compiler shows error. It's
because compiler doesn't know which
function to call. For example,
Ambiguity in Multiple Inheritance
class base1
{
public: void someFunction( ) { .... ... .... }
};
class base2
{public: void someFunction( ) { .... ... .... }
};
class derived : public base1, public base2
{
};
int main()
{
derived obj;
obj.someFunction(); // Error!
}
int main()
{
obj.base1::someFunction( );
// Function of base1 class is called
obj.base2::someFunction();
// Function of base2 class is called.
}
#include<iostream>

using namespace std;


class P {
public:
void print() { cout <<" Inside P"; }
};

class Q : public P { The print function is not present in class R. So


public: it is looked up in the inheritance hierarchy.
void print() { cout <<" Inside Q"; } print() is present in both classes P and Q,
}; which of them should be called? The idea is, if
there is multilevel inheritance, then function is
class R: public Q { }; linearly searched up in the inheritance
hierarchy until a matching function is found.
int main(void)
{
R r;
r.print();
return 0;
}
Inside Q
#include<iostream>
using namespace std;

class Base {
private:
int i, j;
public:
Base(int ii = 0, int jj = 0): i(ii), j(jj) { }
}; Private data members
class Derived: public Base { not accessible
public:
void show(){
cout<<" i = "<<i<<" j = "<<j;
}
};
int main(void) {
Derived d;
d.show();
return 0;
}
#include<iostream>
using namespace std;

class Base1
{
public:
char c;
};

class Base2
{
public:
int c;
}; Compiler Error in "cout << c;“
class Derived: public Base1, public Base2
Use Base2::c; to resolve ambiguity
{
public:
void show() { cout << c; }
};

int main(void)
{
Derived d;
d.show();
return 0;
}
The base class members cannot be directly assigned
using initializer list. We should call the base class constructor in
order to initialize base class members.
#include<iostream>
using namespace std;

class Base
{
public :
int x, y;
public:
Base(int i, int j){ x = i; y = j; }
};

class Derived : public Base


{
public:
Derived(int i, int j):x(i), y(j) {}
void print() {cout << x <<" "<< y; }
};

int main(void)
{
Derived q(10, 10);
q.print(); // Compiler Error
return 0;
}
The base class members cannot be directly assigned
using initializer list. We should call the base class constructor in
order to initialize base class members.
• #include<iostream>
• using namespace std;

• class Base
• {
• public :
• int x, y;
• public:
• Base(int i, int j){ x = i; y = j; }
• };

• class Derived : public Base
• {
• public:
• Derived(int i, int j): Base(i, j) {}
• void print() {cout << x <<" "<< y; }
• };

• int main(void)
• {
• Derived q(10, 10);
• q.print();
• return 0;
• }
A Base class pointer/reference can point/refer to
a derived class object, but the other way is not
possible.
• #include<iostream>
• using namespace std;

• class Base {};

• class Derived: public Base {};

• int main()
• {
• Base *bp = new Derived;
• Derived *dp = new Base;
• }

• Compiler Error in line " Derived *dp = new Base;"


A base class pointer can point to a derived class object, but we can only
access base class member or virtual functions using the base class pointer.
#include<iostream>
using namespace std;

class Base
{
public:
void show()
{
cout<<" In Base ";

};
} Compiler Error in line " cout << bp->x"
class Derived: public Base
{
public:
int x;
void show()
{
cout<<"In Derived ";
}
Derived()
{
x = 10;
}
};

int main(void)
{
Base *bp, b;
Derived d;
bp = &d;
bp->show();
cout << bp->x;
return 0;
}

Potrebbero piacerti anche