unit 2_
unit 2_
• C++ allows to reuse classes. This is done by writing a new class that reuses properties of
existing ones.
is-a relationship - Inheritance is an is-a relationship. We use inheritance only if an is-a relationship is
present between the two classes.
Sub Class: The class that inherits properties from another class is called Subclass or Derived Class.
Super Class: The class whose properties are inherited by subclass is called Base Class or Super class.
Inheritance Example
● A car is a vehicle.
● Orange is a fruit.
● A surgeon is a doctor.
● A dog is an animal.
Access Specifiers in Inheritance
A derived class can access all the non-private members of its base class.
Thus base-class members that should not be accessible to the member functions of derived classes should
be declared private in the base class.
We can summarize the different access types according to - who can access them in the following way −
B B B
class A
class C : protected A
{
{
private: int x;
// z is protected member
protected: int y;
// y is protected member
public: int z;
// x is not accessible
};
};
class D : private A
class B : public A
{
{
// z is private
// z is public
// y is private
// y is protected member
// x is not accessible
// x is not accessible
};
};
Constructors and Destructors in Inheritance
Since, we create objects of the derived class, it is the responsibility of the Derived class
constructor to call the Base class constructor (with or without parameters).
Whenever you create derived class object, first the base class default constructor is
executed and then the derived class's constructor finishes execution.
Note:
1. Suppose, a function with same name and set of arguments is defined in both the derived
class and the based class.
2. Now, if we call this function using the object of the derived class, the function of the derived
class will be executed.
3. This is known as function overriding in C++. The function in derived class overrides the
function in base class.
#include <iostream>
using namespace std; int main() {
Derived classes.
So, when we call print() from the Derived object derived1, the
To access the overridden function of the Base class, we use the scope resolution operator ::
Eg. derived2.Base::print();
Here, this statement
derived2.Base::print();
derived1.print();
return 0;
}
In this program, we have called the overridden function inside the
Mathematics
a,b
accept()
Addition
add()
Class - A
int a
Example of
accept()
Multilevel Inheritance
display()
Class - B
int b
accept()
display()
Class - C
int c
accept()
display()
Example of
Hierarchical Inheritance
Student Employee
Marks Salary
Example of
Multiple Inheritance
Employee_Info
Empid,Salary
Accept3(),Display3()
Ambiguity in Multiple Inheritance
Which swift is
Rohit using..?
Rohit: swift
Ambiguity in Multiple Inheritance
The most obvious problem with multiple inheritance occurs during function overriding.
Suppose, two base classes have a same function which is not overridden in derived class.
If we try to call the function using the object of the derived class, compiler shows error.
This problem can be solved using scope resolution function to specify which function to class either base1 or base2
int main()
derived obj;
}
Virtual Base-Class
Consider the situation where we have one class A which is inherited by two
other classes B and C. Both of these classes are then inherited into another
new class D as shown in figure:
Virtual Base Class
The data members & functions of class A are inherited twice to class D.
Solution:
To resolve this ambiguity when class A is inherited in class B and class C, it is declared as
virtual base class by placing a virtual keyword the inheritances as :
Syntax 2:
class C : public virtual A
{
};
Friend Class
It restricts the access of private members from outside of the class and that is why, a class cannot access
Similarly, a class that doesn’t inherit another class cannot access its protected members.
Friend Class:
- A friend class is a class that can access the private and protected members of a class in which it is
declared as friend.
- This is needed when we want to allow a particular class to access the private and protected
members of a class.
Friend Class
Like friend functions, we can also use a friend class in C++ using the friend keyword.
For example,
Class B
{
//here class B can access private data members of class A
}
Class A
{
friend class B;
}
Now, since classB is a friend class, its member functions can access all members of classA
Friend Class
#include <iostream>
using namespace std; class ABC {
public:
class XYZ { void disp(XYZ obj){
cout<<obj.ch<<endl;
private: cout<<obj.num<<endl;
char ch='A'; }
int num = 11; };
public:
/* This statement would make
class ABC a friend class of XYZ, int main() {
this means that ABC can access ABC obj;
the private and protected members XYZ obj2;
of XYZ class. obj.disp(obj2);
*/ return 0;
friend class ABC; }
};
Pointers in C++
data_type *pointer_name;
• Pointer variable can only contain address of a variable of the same data type.
• The & (immediately preceding a variable name) returns the address of the variable
associated with it.
void main()
{
int a = 10;
int *ptr; //pointer declaration
ptr = &a; //pointer initialization
}
Pointers & Arrays
In C++, pointers can no only store the address of a single variable, it can also store the address of
cells of an array.
Consider this example: int *ptr; • Here, ptr is a pointer variable while
int arr[5]; arr is an int array.
int *ptr;
int arr[5];
ptr = &arr[0];
The addresses for the rest of the array elements are given by &arr[1], &arr[2], &arr[3],
and &arr[4].
Pointing to Every Array Elements
Suppose we need to point to the 3rd element of the array using the same pointer ptr.
So, if ptr points to the 0th element initially, then ptr + 3 will point to the 3rd element.
int *ptr;
For example,
int arr[5];
ptr = arr;
For example,
int *ptr[5];
int arr[5]={1,2,3,4,5};
ptr[0]= &arr[0];
ptr[1]= &arr[1];
ptr[2]= &arr[2];
:
:
Home Assignment:
Write a C++ program to have an array initialized with 10 integer values and a
array pointer. Accept a number from user and traverse the array using the pointer
to check whether the number is present in the array.
Pointers to Functions
• Pointers are used to point some variables, similarly, the function pointer is a pointer used to
point functions.
Eg.
funcPtr=function_name;
Pointers to Function Example
return 0;
}
Pointers to Objects
class Simple
{
public:
int a;
};
int main()
{
Simple obj;
Simple* ptr; // Pointer of class type
ptr = &obj;
3. Member functions are accessed through object pointer using arrow operator ()
ptr display()
4. We can create objects at run-time using “new” operator and refer to it using a pointer
5. Parameters can be passed for object creation: Sample_Class *ptr = new Sample_Class (5, 10);
Pointer to Array of Objects
1. Creating array of objects using pointer Sample_Class *ptr = new Sample_Class [10] ;
• This creates 10 objects and the pointer “ptr” will point to the first object’s
memory location
• ptr++ will make the pointer point at the next object
ptr[i] = new Sample_Class; // separately creates each object in memory and assigns the returned
address to ptr[i]
ptr[i] getdetails(); // Call to member functions for each of the dynamically created objects using
address of that object
“this” Pointer
● C++ provides a keyword 'this', which represents the current object and
passed as a hidden argument to all member functions.
● The this pointer is a constant pointer that holds the memory address of
the current object.
For example, following is the declaration for a pointer to a pointer of type int −
int **var;
Pointers to Derived Class
In C++, we can declare a pointer that points to the address of base class as well as derived class objects.
base b; base
base *bptr;
bptr=&b;
derive d;
bptr=&d; derived
Passing pointers to functions
• If a pointer is passed to a function as a parameter and tried to be modified then the changes made to
the pointer does not reflects back outside that function.
• This is because only a copy of the pointer is passed to the function. It can be said that “pass by
pointer” is passing a pointer by value.
// function to change pointer value cout << "Passing Pointer to function:" << endl;
void changePointerValue(int* p) cout << "Before :" << *ptr<< endl; // displays 23
{
p = &global_var; changePointerValue(ptr)
}
cout << "After :" << *ptr << endl; // displays 23
return 0;
}
Return Pointer from Function
• A function can return data of types int , float, char, etc.
• Similarly, a function can return a pointer to data. The syntax of a function returning a
pointer is as follows:
#include <iostream>
return 0;
}
● If a pointer contains the null value, it is assumed to point to nothing.
Void Pointer
• A void pointer is a pointer that has no associated data type with it.
• A void pointer can hold address of any type and can be type casted to any type.
int a = 10;
char b = 'x';