Inheritance and Pointers
2.1 : Basic Concept of Inheritance
Q.1 Define the term inheritance. :
Ans.: Inheritance is a property in which data members and member
functions of some class are used by some other class.
2.2 : Base Class and Derived Class
Q.2 Explain the term base class and derived class.
Ans. : + The class from which the data members and member functions
are used by another class is called the base class.
The. class which uses the properties of base class and at the same time
can add its own properties is called derived class.
2.3 : Public and Private Inheritance
Q.3 Wr
rite a C++ program to inherit a base class in public mode.
Ans. :
#include
using namespace std;
class Base
{
int x;
public:
void set_x(int n)
{
n;
(2-1)object Oriented Programming 2-2 IS Bi ses
void show_x( )
cout <<"\n x= "<>x;
cout<<"\n Enter the value of y"
cin>>y;
/fusing obj of derived class ba!
obj.set_x(x);
obj.set_y(y); // access member of derives
obj.show_x(); // access member of base class
obj.show_y(); // access member of derived class
Tetum
7 Gulde for Engineering Students
icons
se class member is accessed
id classInheritan
3 ce and Pointe,
Object Oriented Programming 2-
}
Output
Enter the value of x30
Enter the value of y70
x= 30
y= 70
In above program the obj is an object of derived class. Using obj we are
accessing the member function of base class. The derived class inherits
base class using an access specifier public.
oo Write a C++ program to inherit base class In private mode.
8. :
#include
using namespace std;
class Base
{
int x;
public:
void set_x(int n)
{
x=n;
}
void show x( )
{
cout <<"\nx
}
k
// Inherit as private
class derived : private Base
{
int yi;
public:
void set_y(int n)
"<—rorer
void show_y()
{
cout <<"\n y= "<>x;
cout<<"\n Enter the value of y";
cin>>y;
obj.set_x(x); // error: not accessible
obj.set_y(y); :
obj.show_x(); // access member of base class
obj.show_y(); // error:not accessible
Tetum 0;
}
As indicated by the comments the above program will generate error
messages “not accessible”. This is because the derived class inherits the
base class privately. Hence the public members of base class become
Private to derived class.
4: Protected Members
Q.5 Explain why and when do we use protected instead of private ?
S&P [SPU : Dec.-15, Marks 4]
A Gulde for Engineering StudentsObject Oriented Programming — 2-5 Inheritance and Pointe,
rs
‘Ans. The protected access specifier is equivalent to the pri,
: le
specifier with the sole exception that protected members of a base clasy
le to members of any class derived from that base, Outs, de
protected members are not accessible,
are accessible
the base or derived classes,
Thus normally protected access specifier is used in the situations when the
immediate derived class members want to access the base class members
but the derived-derived class members are prohibited to access the base
class members.
2.5 : Relationship between Base Class and Derived Class
Q.6 What are the advantages of inheritance by
‘Ans. : One of the key benefits of inheritance is to minimize the amount
of duplicate code in an application by sharing common code amongst
several subclasses.
. Reusability : The base class code can be used by derived class
without any need to rewrite the code.
2. Extensibility : The base class logic can be extended in the derived
classes. :
3. Data hiding : Base class can decide to keep some data private so that
it cannot be altered by the derived class.
” 4. Overriding : With inheritance, we will be able to override the
methods of the base class so that meaningful implementation of the
base class method can be designed in the derived class.
2.6 : Constructor and Destructor in Derived Class
Q,7 Explain the execution process of constructors and destructors
in derived class.
Ans, : ¢ When we create an object for derived class then first of all the
Base class constructor is called and after that the Derived olass
constructor is called.
ee
‘A Guide for Engineering SudensOriented Programmi .
Object gr ia, Inheritance and Pointers
«When the main function finishes running, the derived class's destructor
will get called first and after that the Base class destructor will be
called.
« This is also called as chain of constructor calls,
class Base {
public:
Base()
{ cout << "Base constructor" << endl; }
~Base()
{ cout << “Base destructor" << endl; }
i
class Derived:public Base {
public:
Derived()
{cout << “Derived constructor” << endl; }
~Derived ()
{cout << “Derived destructor” <<-endl; }
k
void main()
{
Derived obj;
}
The output of above code will be invoking of base class constructor, then
derived class constructor, then derived class destructor and finally base
2.7 : Overriding Member Functions
Q.8 Explain the function overriding concept with suitable example
Ans. : Definition : Redefining a function in a derived class is called
function overriding.
For example - Consider following C++ program that uses the same
function name i.e. print_msg in base class and derived class. The
destructor.
‘A Guide for Engineering StudentsI
ject Oriented Programnins 2-7 inheritance an Poin,
function print_msB in
print_msg
class A
{
private:
n derived class overrides the base class func
ion,
int a,b;
public:
void get_msg()
{
a=10;
b=20;
}
void print_msg().
{
int ¢;
c=atb;//performing addition
cout<<"\n C(10+20)= "<
using namespace std;
class Base
{
public:
; Fig. Q.10.1 Single
eal Inheritance
void set_x(int n)
void show_x()
{ ‘
cout << "“\n\tx =" << x;
}
ki
class derived : public Base
s
int yi
public:
A Guide for Engineering Sudere
|
47 sy
object Oriented Programming 2
Inheritance and Pointers
void set_y(int n)
{
y=
}
void show_xy()
{
cout < "\n\t x
cout < "\n\t y
}
<> x; :
cout << “\n Enter the value of y";
cin >> y;
obj.set_x(x);//inherits base class
obj.set_y(y); // access member of derived class
obj.show_x();//inherits base class
obj.show_xy(); // access member of derived class
retum 0;
2, Multilevel inheritance :
It is a kind of inheritance in which
the derived class is derived. from a
i 5 Class B Derived
single base class which itself is a
derived class.
class A
{ Derived-derived
Protected:
int x, Fig. Q.10.2 Multilevel Inheritance
A Gulde for Engineering StudentsInheritance and Poin,
Object Oriented Programming 2-11
Public:
void get_a(int a)
{ x=a; }
void put_a()
{ cout<< "\n The value of x is "<< x: }
h
class B:public A
{
Protected:
int yi
public:
void get_b(int b)
{ y=b; }
void put_b()
{ cout<<"\n The value of y is "<
class base {
public:
int i
ki
class derived1:virtual public base
public:
int ji
ki
class derived2:virtual public base
{
public:
int k;
ki
//derived3 is inherited from derived and derived2
/fout only one copy of base class is inherited,
class derived3:public derived1 public derived2
C7 .
ee
é
Guide for Engineering Sud
uaCs Inheritance and Pointers
a
public:
int sum()
{
return i+j+k;
}
ki
void main()
& sived3 obj;
obj.i=10;
obj.
obj.k=30;
cout<" The sum is = "getarea();
cout<<"\n Calculating area of triangle";
* t.setarea(num1,num2);
p= &t;
cout << "\nArea of Triangle is: "<< p->getarea() ;
return 0;
} :
The above proj
is 100.
Q.14 What are abstract
as an abstract class ani
engineering, science, medical etc. from the student
their object and process them.
Ans, :
#include
#include
gram will display area of square as 200 and area of triangle
classes ? Write a program having student
d create many derived classes such as
Create
‘A Gulde for Engineering StudentsInherit:
Object Oriented Programming 2-21 pean Py
using namespace std;
class Student
{
char name[10};
public:
void SetName(char n/10])
{
strcpy(name,n);
}
void GetName(char n[10])
{
strepy(n,name);
} 5
virtual void qualification()=0;
ki
class Engg:public Student .
public:
void qualification()
{
char n[10};
GetName(n);
cout<>nm;
e.SetName(nm);
s=ke;
s->qualification();
cout<<"\n Enter the name: "<>nm;
mSetName(nm);
s=&m;
8->qualification();
retum 0;
Output
Enter the name:
Ramesh
Ramesh is a an engineering student
Enter the name:
Suresh
Suresh is a medical student
Q.18 Explain the friend class concept.
‘Ans. Similar to a friend function one can declare a class as.a friend to
another class. This allows the friend class to access the private data
Members of the another class.
A Gulde for Engineering StudentsInheritance and poy
Object Oriented Programming 2-23 me Pointer
For example
class A
{
Private:
int data;
friend class B;//class B is friend of class A
Public:
A()//constructor
{
data = 5;
}
ki
class B
{
public:
int sub(int x)
{
A obj1; //object of class A
//the private data of class A is accessed in class B
// ata contains § and x contains 2
Tetum obji.data — x;
a
2.14 : Nested Class
Q.16 What is nested class ? Write a C++ program to demonstrate
the concept of nested class
Ans. : :
k
‘When one class is defined inside the other class then it is called
the nested’ class. The nested class can access the data member of the
outside class. Similarly the data member of the nested can be accessed
from the main. Followin,
: ig is a simple C++ program that illustrates the U¢
of nested class.
A Guide for Engineering Suden®Objest OfeNes Erotrasielig 224 Inheritance and Pointers
es erlltC —””—C
ponte
‘The program for demonstration of nested class
seenaennennenaeney
#include
class outer
{
public:
int a; // Note that this member is public
class inner
{
public:
void fun(outer *o,int val)
{
o->a = val:
cout<<"a= "<a;
}
}i//end of inner class
}i//end of outer class
void main()
{
outer obj1;
outer::inner obj2; .
obj2.fun(&obj1,10); //invoking the function of inner class
Output
a= 10
a
AGuide for Engineering Studentsos Inheritance and Pointer,
iented Programming
Object Oren Programming _ 2225
2.15 : Pointers : Declaration and Initialization
itialization.
Q.47 Define pointer and explain ite Inlhl M coresents the memo
: i : i is a vari -
ee = re The’ purpose of pointer is t0 hold the
memory location and not the actual value. For example -
a=10; /*storing some value in a*/
ptr=&a;/*storing address of a in ptr*/
b="ptr;/*getting value from address in ptr and storing it in b*/
2.16 : Memory Management : New and Delete
Q.18 Explain the purpose of new and delete operators with suitable
examples. :
Ans.: The dynamic memory allocation is done using an operator new.
For example : int *p;
p=new int;
We can allocate the memory for more than one élement. For instance if
we want to allocate memory of size in for 5 elements we can declare.
a
p=new int(5];
The memory can be deallocated using the delete operator.
For example : delete p;
C++ Program using new and delete operators
int main () :
{
int in;
int *p;
cout << "How many numbers would you like to type? ";
cin >> i; :
P= new int(i];//dynamic memory allocation
if (p == 0)
e
A Guide for Engineering Sué™vject Oriented Programming 2-26 Inheritance and Pointers
cout << “Error: memory could not be allocated”;
else
{
for (n=0; n> pin};
}
cout << “You have entered:
for (n=0; n getVal()< num=num;
}
void print_val()
{
cout<<“\n The value is "<
using namespace std; e
void main()
{
int a[10), i, n, *ptr, key;
cout<<"\a How Many eléments are there in an array ? ';
cin>>n; :
Cout<<"\n Enter the elements in an array ";
for (i = 0; i>ali);
ee
1A Guide for Engineering StudentsInheritance and Pointe,
Object Oriented Programming — 2 =
ago addrose in ptr
Ptr = &a(0);/*copying the be
cout<<"\n Enter the Key element %
cin> >key;
for (1 = 0; iptr2
ptrl—=ptr2
pitl<=ptr2
The relational operations are possible on pointer
variable while comparing two pointers.
ptrl>=ptr2
pirl !=ptr2
2.22 : Arrays of Pointers
Q.24 What is array of pointers ? Explain with pseudo code.
‘Ans, : The array of pointers means the array locations are containing the
address of another variable which is holding some value, For example,
lO) a(t] al2)
x y z
65524 65522 65520
Fig. Q.24.1 Array of pointers
‘The array of pointers is the concept which is mainly used when we want
to store the multiple strings in an array. Here we have simply taken the
integer values in three different variables x, y and z. The addresses of x,
y and z are stored in the array a, This concept is implemented by
following simple C++ program.
#include
using namespace std;
void main()
{
int *a(10];/*array is declared as of pointer type*/
inti, x, y, 2;
‘A Guide for Engineering StudentsObject Oriented Programming 2-31 Inheritance and Pointers
cout<<"\n Enter The Array Elements ";
cin>x>>y>>2;
[0] = &x;/*storing the address of each variable in array location */
all] = &y;
al2] = &
for (i
{
0; i<3; i++)
cout<<"\nThe element "<<*ali]<<" is at location "<>r, :
display(area, 1);/*function is passed as a parameter to another
function*/
}
void display(float(*fptr)(int), int r)
{
/*call to pointer to function*/
cout<<"\n The area of circle is "<(*fptr)(r);
}
float area(int r)
{
retum (3.14*r*z);
}
Q26 Write a program to find the sum of
an array to a function using pointer.
Ans. :
#include
an array Arr by passing
EP [SPPU : Dec.-17, Marks 4]
using namespace std;
{nt fun(const int Sarr, int size)
{
int cum = *arr;
i < size; ++i)
“A Guide for Engineering StudentsObject Oriented Programming 2-33 Inheritance and Pointer
{
sum = sum+ *(arr+i);
}
retum sum;
}
int main()
{
const int SIZE =
int numbers|SIZE] = {10, 20, 90, 76, 22};
cout << "The sum of array is: "<
using namespace std;
void main()
{
void display(float(*)(int), int);
float area(int);
intr;
cout<<"\n Enter the radius ";
cin>>r;
display(area, r);/*function is passed as a
parameter to another function*/
}
void display(float(*fptr)(int), int 1)
if
/*call to pointer to function*/
cout<<"\n The area of circle is "<(*fptz)(r);
}
float area(int r)
{
retum(3.14*r*r);
2.24 : Pointers to Pointers
Q28 is pointers to pointers ? Explain. —
Ans. Pe a point to other pointer variables which brings the
multiple level of indirection.
Void main()
{
AGuide for Engineering. StudentsInheritance aud po;
i -35
Object Oriented Programming? ‘.
int a;
int *ptrl, **ptr2;
&ptrl;
cout<<"\n a = "<a = 100;
200;
ptr->display();
ptr->
Output
2.26 : Null Pointer
Q30 What is NULL pointer ? Explain.
Ans.: » Pointer that are not initialized with valid address may cause
Some substantial damage. For this reason it is important to initialize them,
The standard initialization is to the constant NULL.
“Using the NULL value as a pointer will cause an error on almost all
systems. :
a= 100
b= 200
eT
‘A Guide for Engineering StudentsInheritance and Pointers
Object Oriented Programming 2-37
© Literal meaning of NULL pointer is a pointer which is pointing to
nothing.
* NULL pointer points the base address of segment.
Following is a simple program that illustrates the problem of Null pointer
[rttees sees
Program for illustrating null pointer problem
oy)
#include
#include
void main()
{
char *str=NULL;
strepy(str,"HelloFriends");
cout