2. Unit 4:Inheritance:
.Inheritance – basics, using super, creating a multi level hierarchy,
when constructor are called, method overriding, dynamic method
dispatch, using abstract classes, using final with inheritance, Wrapper
Classes.
3. Inheritance is one of the key features of Object-oriented programming in C++. It
allows us to create a new class (derived class) from an existing class (base class).
The derived class inherits the features from the base class and can have additional features of
its own. For example,
class Animal {
// eat() function
// sleep()
function
};
class Dog : public
Animal {
// bark() function
};
4. Here, the Dog class is derived from the Animal class. Since Dog is derived from Animal,
members of Animal are accessible to Dog.
5. Notice the use of the keyword public while inheriting Dog from Animal.
class Dog : public Animal {...};
Inheritance is an is-a relationship. We use inheritance only if an is-a relationship is
present between the two classes.
6. Example
#include <iostream>
// C++ program to demonstrate inheritance
using namespace std;
// base class
class Animal {
public:
void eat() {
cout << "I can eat!" << endl;
}
void sleep() {
cout << "I can sleep!" << endl;
}
};
// derived class
class Dog : public Animal {
public:
void bark() {
cout << "I can bark! Woof woof!!" <<
endl;
}
};
int main() {
// Create object of the Dog class
Dog dog1;
// Calling members of the base class
dog1.eat();
dog1.sleep();
// Calling member of the derived class
dog1.bark();
return 0;
}
8. C++ protected Members
The access modifier protected is especially relevant when it comes to C++
inheritance.
Like private members, protected members are inaccessible outside of the class.
However, they can be accessed by derived classes and friend classes/functions.
We need protected members if we want to hide the data of a class, but still want that
data to be inherited by its derived classes.
9. #include <iostream>
#include <string>
using namespace std;
// base class
class Animal {
private:
string color;
protected:
string type;
public:
void eat() {
cout << "I can eat!" << endl;
}
void sleep() {
cout << "I can sleep!" << endl;
}
void setColor(string clr) {
color = clr;
}
10. string getColor() {
return color;
}
};
// derived class
class Dog : public Animal {
public:
void setType(string tp) {
type = tp;
}
void displayInfo(string c) {
cout << "I am a " << type << endl;
cout << "My color is " << c << endl;
}
void bark() {
cout << "I can bark! Woof woof!!" <<
endl;
}
};
int main() {
// Create object of the Dog class
Dog dog1;
// Calling members of the base class
dog1.eat();
dog1.sleep();
dog1.setColor("black");
// Calling member of the derived class
dog1.bark();
dog1.setType("mammal");
// Using getColor() of dog1 as argument
// getColor() returns string data
dog1.displayInfo(dog1.getColor());
return 0;
}
11. output
I can eat!
I can sleep!
I can bark! Woof woof!!
I am a mammal
My color is black
12. Here, the variable type is protected and is thus accessible from the derived class Dog. We can
see this as we have initialized type in the Dog class using the function setType().
On the other hand, the private variable color cannot be initialized in Dog.
Also, since the protected keyword hides data, we cannot access type directly from an
object of Dog or Animal class.
13. Public, protected and private inheritance in C++
● Public inheritance makes public members of the base class public in the
derived class, and the protected members of the base class remain protected in
the derived class.
● protected inheritance makes the public and protected members of the base class
protected in the derived class.
● privateinheritance makes the public and protected members of the base class
private in the derived class.
14. 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
};
c}
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
15. C++ public Inheritance
using namespace std;
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
// function to access private member
int getPVT() {
return pvt;
}
};
class PublicDerived : public Base {
public:
// function to access protected member
from Base
int getProt() {
return prot;
}
};
int main() {
PublicDerived object1;
cout << "Private = " << object1.getPVT()
<< endl;
cout << "Protected = " <<
object1.getProt() << endl;
cout << "Public = " << object1.pub <<
endl;
return 0;
}
16. Output
Private = 1
Protected = 2
Public = 3
As a result, in PublicDerived:
● prot is inherited as protected.
● pub and getPVT() are inherited
as public.
● pvt is inaccessible since it is
private in Base.
Since private and protected
members are not accessible from
main(), we need to create public
functions getPVT() and getProt() to
access them:
17. Accessibility in public Inheritance
Accessibility private
members
protected
members
public
members
Base Class Yes Yes Yes
Derived Class No Yes Yes
18. C++ protected Inheritance
Here, we have derived PrivateDerived from Base in private mode.
As a result, in PrivateDerived:
● prot, pub and getPVT() are inherited as private.
● pvt is inaccessible since it is private in Base.A
● As we know, private members cannot be directly accessed from
outside the class. As a result, we cannot use getPVT() from
PrivateDerived.
● That is also why we need to create the getPub() function in
PrivateDerived in order to access the pub variable.
19. protected Inheritance Example
#include <iostream>
using namespace std;
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
// function to access private
member
int getPVT() {
return pvt;
}
class ProtectedDerived : protected Base {
public:
// function to access protected member
from Base
int getProt() {
return prot;
}
// function to access public member from
Base
int getPub() {
return pub;
}
};
int main() {
ProtectedDerived object1;
cout << "Private cannot be accessed." <<
endl;
cout << "Protected = " << object1.getProt()
<< endl;
cout << "Public = " << object1.getPub() <<
endl;
return 0;
21. Accessibility in private Inheritance
Accessibility private
members
protected
members
public
members
Base Class Yes Yes Yes
Derived
Class
No Yes
(inherited as
private
variables)
Yes
(inherited as
private
variables)
22. C++ Multiple Inheritance
A class can also be derived from more than one base class, using a comma-
separated list
23. class MyClass {
public:
void myFunction() {
cout << "Some content in parent
class." ;
}
};
// Another base class
class MyOtherClass {
public:
void myOtherFunction() {
cout << "Some content in another
class." ;
}
};
/
/ Derived class
class MyChildClass: public MyClass,
public MyOtherClass {
};
int main() {
MyChildClass myObj;
myObj.myFunction();
myObj.myOtherFunction();
return 0;
}
Output :
Some content in parent class.
Some content in another class.
Some content in parent class.
Some content in another class.
Some content in parent class.
Some content in another class.
24. class derived-class: visibility-mode base-class
Visibility mode is used in the inheritance of C++ to show or relate how base
classes are viewed with respect to derived class. When one class gets
inherited from another, visibility mode is used to inherit all the public and
protected members of the base class. Private members never get inherited and
hence do not take part in visibility. By default, visibility mode remains
"private".
25. Hierarchical Inheritance in C++
Hierarchical Inheritance in C++ refers to the type of inheritance that has a
hierarchical structure of classes. A single base class can have multiple
derived classes, and other subclasses can further inherit these derived
classes, forming a hierarchy of classes. The following diagram illustrates
the structure of Hierarchical Inheritance in C++.
Hierarchical Inheritance in C++ is useful in the cases where a hierarchy has to be
maintained. Most of the schools and colleges maintain the data of their students in
hierarchical form. For example, a college has to maintain the data of the engineering
students and segregate them according to their branches such as the IT branch,
mechanical branch, and so on. You can achieve such a scenario can by Hierarchical
26.
27. You can use the following syntax to achieve Hierarchical Inheritance in C++:
class base_class
{ //data members , //member functions };
class derived_class1 : visibility_mode base_class
{ //data members, //member functions };
class derived_class2 : visibility_mode base_class
{ //data members, //member functions
};
28. ● visibility_mode: It provides the visibility mode in the class declaration. It specifies how
the members of the base class will be inherited by the derived class. In the case of
Hierarchical Inheritance in C++, it separately defines the visibility mode with every
derived class during inheritance.
● base_class: This is the name of the class from which the derived class inherits its
properties and characteristics.
● derived_class1: This is the name of the first derived class that inherits the properties of
the base class using the visibility mode.
● derived_class2: This is the name of the second derived class that inherits the properties of
the base class using the visibility mode.
NOTE: There can be n number of derived classes of a single base class.
29. Visibility Modes in Hierarchical Inheritance in C++
The visibility mode determines control over the base class members within the child
classes by specifying how the base class features will be inherited by the derived class.
There are three types of visibility modes of Hierarchical Inheritance in C++:
Public Visibility Mode
Public visibility mode does not affect the working of access specifiers. All the access specifiers
remain as they are. This means that the private members remain private i.e., not accessible by
anyone, public members remain public i.e., accessible in all the derived classes as well outside the
derived classes. And protected members remain protected, i.e., accessible only within the derived
classes.
30. Private Visibility Mode
In private visibility mode, both the public and protected access specifiers become private.
This makes all the members inaccessible outside of the class in which they are defined. You
can only access them through the member functions of the same class. And since the private
members can not be inherited, you can also not inherit further these members.
In protected visibility mode, the public members become protected and the private and
protected members remain the same. This means that you cannot access the public members,
just like the protected members outside the derived classes. The private members remain
inaccessible even in the derived classes and can only be accessed by the member functions of
the class in which the private members are defined.
31. C++ Hybrid Inheritance
The inheritance in which the derivation of a class involves more than one form of any
inheritance is called hybrid inheritance. Basically C++ hybrid inheritance is
combination of two or more types of inheritance. It can also be called multi path
inheritance.
Following block diagram highlights the concept of hybrid inheritance which involves
single and multiple inheritance.
32.
33. C++ Hybrid Inheritance Syntax
Class A
{
.........
};
class B : public A
{
..........
} ;
class C
{
...........
};
class D : public B, public C
{
...........
};
34. C++ Hybrid Inheritance Example
#include <iostream>
// hybrid inheritance.cpp
using namespace std;
class A
{
public:
int x;
};
class B : public A
{
public:
B() //constructor to initialize
x in base class A
{
x = 10;
}
};
class C
{
public:
int y;
C() //constructor to initialize y
{
y = 4;
}
};
class D : public B, public C //D is derived
from class B and class C
{
public:
void sum()
{
cout << "Sum= " << x + y;
}
};
35. int main()
{
D obj1; //object of derived class
D
obj1.sum();
return 0;
} //end of program
Sum= 14/tmp/Ql7NNck85I.o
Sum= 14
36. Virtual class
VVirtual base classes are used in virtual inheritance in a way of preventing multiple
“instances” of a given class appearing in an inheritance hierarchy when using multiple
inheritances.
Need for Virtual Base Classes:
Consider the situation where we have one class A .This class is A is inherited by two other
classes B and C. Both these class are inherited into another in a new class D as shown in
figure below.
37. As we can see from the figure that data
members/function of class A are inherited twice to
class D. One through class B and second through
class C. When any data / function member of class A
is accessed by an object of class D, ambiguity arises
as to which data/function member would be called?
One inherited through B or the other inherited
through C. This confuses compiler and it displays
error.
38. #include <iostream>
using namespace std;
class A {
public:
void show()
{
cout << "Hello form A n";
}
};
class B : public A {
};
class C : public A {
};
class D : public B, public C {
};
int main()
{
D object;
object.show();
}
Output
26 | object.show();
| ^~~~
/tmp/Ql7NNck85I.cpp:8:10: note:
candidates are: 'void A::show()'
8 | void show()
| ^~~~
/tmp/Ql7NNck85I.cpp:8:10: note:
'void A::show()'
39. To resolve this ambiguity when class A is inherited in both class B and class C, it is declared
as virtual base class by placing a keyword virtual as :
Syntax
Syntax 1:
class B : virtual public A
{
};
Syntax 2:
class C : public virtual A
{
};
40. #include <iostream>
using namespace std;
class A {
public:
int a;
A() // constructor
{
a = 10;
}
};
class B : public virtual A {
};
class C : public virtual A {
};
class D : public B, public C {
};
int main()
{
D object; // object creation of class d
cout << "a = " << object.a << endl;
return 0;
}
41. Output
a = 10
The class A has just one data member a which is public. This class is virtually
inherited in class B and class C. Now class B and class C becomes virtual base class
and no duplication of data member a is done.
42. #include <iostream>
using namespace std;
class A {
public:
void show()
{
cout << "Hello from A n";
}
};
Output
Hello from A
class B : public virtual A {
};
class C : public virtual A {
};
class D : public B, public C {
};
int main()
{
D object;
object.show();
}
43. Sometimes implementation of all function cannot be provided in a base class because we
don’t know the implementation. Such a class is called abstract class. For example, let
Shape be a base class. We cannot provide implementation of function draw() in Shape, but
we know every derived class must have implementation of draw(). Similarly an Animal
class doesn’t have implementation of move() (assuming that all animals move), but all
animals must know how to move. We cannot create objects of abstract classes.
44. Constructors in derived class
In case of multiple inheritance, the base class takes the responsibility of supplying initial
values to its base classes, we supply the initial values that are required by all the classes
together, when a derived class object is declared. How are they passed to the class
constructors so that they can do their job
Example
d(int a1,int a2,float b1,float b2,int d1)
A (a1,a2)
B (b1,b2)
45. Constructors in derived class Example
# include
Using namespace std;
Class alpha{
Int x;
Public:
Alpha (int i)
{
x=i;
cout<<”x=”<<x<<”n”;
}
Void show x(void)
{ cout<<”x=”<<x<< ”n”;
};
Class beta {
Float y;
Public:
beta(float j)
{
y=j;
cout<<” beta intilizedn” ;
}
Void show_y(void
{
cout<<”y=” <<y<<”n”;
}
Class gamma: public beta,public alpha
{
Int m,n;
public:
47. Question bank
Q.1 write syntax to define derived class in c++
Q.2 what does inheritance means in c++
Q.3. What are the different forms of inheritance ? Give an example of each.
Q.4.when do we use the protected visibility specifier to a class member?
Q5.Describe the syntax of multiple inheritance. When do we use such inheritance
Q.6.What is output of following programA
Q.7. What is output of following program B
48. What is output of program A
#include <iostream>
using namespace std;
class A {
public:
void show()
{
cout << "Hello from A n";
}
};
class B : public virtual A {
};
class C : public virtual A {
};
class D : public B, public C {
};
int main()
{
D object;
object.show();
}
49. Program B
#include <iostream>
using namespace std;
class A {
public:
void show()
{
cout << "Hello from A n";
}
};
Output
Hello from A
class B : public virtual A {
};
class C : public virtual A {
};
class D : public B, public C {
};
int main()
{
D object;
object.show();
}
50. Unit 5
Introduction Dynamic and Static allocation of memory Pointer variable Pointer
and arrays Arrays of pointers Dynamic memory allocation operators this pointer
Definition Type of polymorphism Definition of function overloading and
operator overloading Operator overloading and friend functions Syntax of
operator overloading Overloading of unary and binary operator
Constructor overloading.