Unit 3-Inheritance

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

Object Oriented Programming using c++

Unit 3:- Inheritance

Concept of Inheritance:-
The capability of a class to derive properties and characteristics from another class is
called Inheritance.
Inheritance is a feature or a process in which, new classes are created from the existing classes. The
new class created is called “derived class” or “child class” and the existing class is known as the
“base class” or “parent class”. The derived class now is said to be inherited from the base class.
derived class inherits the base class, it means, the derived class inherits all the properties of the base
class, without changing the properties of base class and may add new features to its own. These
new features in the derived class will not affect the base class. The derived class is the specialized
class for the base class.
 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 a subclass is called Base Class or
Superclass.

Implementing inheritance in C++: For creating a sub-class that is inherited from the base class we
have to follow the below syntax.
Derived Classes: A Derived class is defined as the class derived from the base class.

Syntax:
class <derived_class_name> : <access-specifier> <base_class_name>
{
//body
}
 Where
class — keyword to create a new class

derived_class_name — name of the new class, which will inherit the base class

access-specifier — either of private, public or protected. If neither is specified, PRIVATE
is taken as default.

base-class-name — name of the base class

Mrs. P.D.Titavekar 1
Object Oriented Programming using c++
Note: A derived class doesn’t inherit access to private data members. However, it does
inherit a full parent object, which contains any private members which that class declares.

Example:
1. class ABC : private XYZ //private derivation
{ }
2. class ABC : public XYZ //public derivation
{ }
3. class ABC : protected XYZ //protected derivation
{ }
4. class ABC: XYZ //private derivation by default
{ }
Note:
 When a base class is privately inherited by the derived class, public members of the base
class becomes the private members of the derived class and therefore, the public members
of the base class can only be accessed by the member functions of the derived class. They
are inaccessible to the objects of the derived class.

On the other hand, when the base class is publicly inherited by the derived class, public
members of the base class also become the public members of the derived class. Therefore,
the public members of the base class are accessible by the objects of the derived class as
well as by the member functions of the derived class.

1. // Example: define member function without argument within


// the class

#include <iostream>
using namespace std;

class Person {
int id;
char name[100];

public:
void set_p()
{
cout << "Enter the Id:";
cin >> id;
cout << "Enter the Name:";
cin >> name;
}

void display_p()
{
cout << endl <<"Id: "<< id << "\nName: " << name <<endl;
}
};

class Student : private Person {


char course[50];
int fee;

public:
void set_s()

Mrs. P.D.Titavekar 2
Object Oriented Programming using c++
{
set_p();
cout << "Enter the Course Name:";
cin >> course;
cout << "Enter the Course Fee:";
cin >> fee;
}

void display_s()
{
display_p();
cout <<"Course: "<< course << "\nFee: " << fee << endl;
}
};

int main()
{
Student s;
s.set_s();
s.display_s();
return 0;
}

Output:
Enter the Id: 101
Enter the Name: Dev
Enter the Course Name: GCS
Enter the Course Fee:70000

Id: 101
Name: Dev
Course: GCS
Fee: 70000

2. // Example: define member function without argument outside the class

#include<iostream>
using namespace std;

class Person
{
int id;
char name[100];

public:
void set_p();
void display_p();
};

void Person::set_p()
{
cout<<"Enter the Id:";
cin>>id;
cout<<"Enter the Name:";
Mrs. P.D.Titavekar 3
Object Oriented Programming using c++
cin>>name;
}

void Person::display_p()
{
cout<<endl<<"id: "<< id<<"\nName: "<<name;
}

class Student: private Person


{
char course[50];
int fee;

public:
void set_s();
void display_s();
};

void Student::set_s()
{
set_p();
cout<<"Enter the Course Name:";
cin>>course;
cout<<"Enter the Course Fee:";
cin>>fee;
}

void Student::display_s()
{
display_p();
cout<<"\nCourse: "<<course<<"\nFee: "<<fee<<endl;
}

int main()
{
Student s;
s.set_s();
s.display_s();
return 0;
}

Output:
Enter the Id: 101
Enter the Name: Dev
Enter the Course Name: GCS
Enter the Course Fee: 70000
Id: 101
Name: Dev
Course: GCS
Fee: 70000

3. // Example: define member function with argument outside the class

#include<iostream>

Mrs. P.D.Titavekar 4
Object Oriented Programming using c++
#include<string.h>
using namespace std;

class Person
{
int id;
char name[100];

public:
void set_p(int,char[]);
void display_p();
};

void Person::set_p(int id,char n[])


{
this->id=id;
strcpy(this->name,n);
}

void Person::display_p()
{
cout<<endl<<id<<"\t"<<name;
}

class Student: private Person


{
char course[50];
int fee;
public:
void set_s(int,char[],char[],int);
void display_s();
};

void Student::set_s(int id,char n[],char c[],int f)


{
set_p(id,n);
strcpy(course,c);
fee=f;
}

void Student::display_s()
{
display_p();
cout<<"t"<<course<<"\t"<<fee;
}

main()
{
Student s;
s.set_s(1001,"Ram","B.Tech",2000);
Mrs. P.D.Titavekar 5
Object Oriented Programming using c++
s.display_s();
return 0;
}
Output
Child id is: 7
Parent id is: 91

Modes of Inheritance: There are 3 modes of inheritance.


1. Public Mode: If we derive a subclass from a public base class. Then the public member of the
base class will become public in the derived class and protected members of the base class will
become protected in the derived class.
2. Protected Mode: If we derive a subclass from a Protected base class. Then both public members
and protected members of the base class will become protected in the derived class.
3. Private Mode: If we derive a subclass from a Private base class. Then both public members and
protected members of the base class will become Private in the derived class.

Note: The private members in the base class cannot be directly accessed in the derived class, while
protected members can be directly accessed. For example, Classes B, C, and D all contain the
variables x, y, and z in the below example

4.// C++ Implementation to show that a derived class


// doesn’t inherit access to private data members.
// However, it does inherit a full parent object.
class A {
public:
int x;

protected:
int y;

private:
int z;
};

class B : public A {
// x is public
// y is protected
// z is not accessible from B
};

class C : protected A {
// x is protected
// y is protected
// z is not accessible from C
};

class D : private A // 'private' is default for classes


{
// x is private
// y is private
// z is not accessible from D
};
Mrs. P.D.Titavekar 6
Object Oriented Programming using c++

Types of Inheritance in C++


1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one class. i.e.
one subclass is inherited by one base class only.

Syntax:
class subclass_name : access_mode base_class
{
// body of subclass
};

OR

class A
{
... .. ...
};
class B: public A
{
... .. ...
};

Mrs. P.D.Titavekar 7
Object Oriented Programming using c++

1.// C++ program to explain


// Single inheritance
#include<iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};

// sub class derived from a single base classes


class Car : public Vehicle {

};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}

Output
This is a Vehicle

2.// Example:

#include<iostream>
using namespace std;

class A
{
protected:
int a;

public:
void set_A()
{
cout<<"Enter the Value of A=";
cin>>a;

}
void disp_A()
{
cout<<endl<<"Value of A="<<a;
}
};
Mrs. P.D.Titavekar 8
Object Oriented Programming using c++

class B: public A
{
int b,p;

public:
void set_B()
{
set_A();
cout<<"Enter the Value of B=";
cin>>b;
}

void disp_B()
{
disp_A();
cout<<endl<<"Value of B="<<b;
}

void cal_product()
{
p=a*b;
cout<<endl<<"Product of "<<a<<" * "<<b<<" = "<<p;
}

};

main()
{

B _b;
_b.set_B();
_b.cal_product();

return 0;

Output:- Enter the Value of A= 3 3 Enter the Value of B= 5 5 Product of 3 * 5 = 15

3.// Example:

#include<iostream>
using namespace std;

class A
{
protected:
int a;

public:
void set_A(int x)
{
a=x;
Mrs. P.D.Titavekar 9
Object Oriented Programming using c++
}

void disp_A()
{
cout<<endl<<"Value of A="<<a;
}
};

class B: public A
{
int b,p;

public:
void set_B(int x,int y)
{
set_A(x);
b=y;
}

void disp_B()
{
disp_A();
cout<<endl<<"Value of B="<<b;
}

void cal_product()
{
p=a*b;
cout<<endl<<"Product of "<<a<<" * "<<b<<" = "<<p;
}

};

main()
{
B _b;
_b.set_B(4,5);
_b.cal_product();

return 0;
}

Output
Product of 4 * 5 = 20

2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit from
more than one class. i.e one subclass is inherited from more than one base class.

Mrs. P.D.Titavekar 10
Object Oriented Programming using c++

Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
// body of subclass
};
class B
{
... .. ...
};
class C
{
... .. ...
};
class A: public B, public C
{
... ... ...
};
Here, the number of base classes will be separated by a comma (‘, ‘) and the access mode for every
base class must be specified.

1.// C++ program to explain


// multiple inheritance
#include <iostream>
using namespace std;

// first base class


class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// second base class


class FourWheeler {
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle\n";
}
};

// sub class derived from two base classes


class Car : public Vehicle, public FourWheeler {
};

// main function
Mrs. P.D.Titavekar 11
Object Oriented Programming using c++
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}

Output
This is a Vehicle
This is a 4 wheeler Vehicle

2. // Example:

#include<iostream>
using namespace std;

class A
{
protected:
int a;

public:
void set_A()
{
cout<<"Enter the Value of A=";
cin>>a;

void disp_A()
{
cout<<endl<<"Value of A="<<a;
}
};

class B: public A
{
protected:
int b;

public:
void set_B()
{
cout<<"Enter the Value of B=";
cin>>b;
}

void disp_B()
{
cout<<endl<<"Value of B="<<b;
}
};

Mrs. P.D.Titavekar 12
Object Oriented Programming using c++
class C: public B
{
int c,p;

public:
void set_C()
{
cout<<"Enter the Value of C=";
cin>>c;
}

void disp_C()
{
cout<<endl<<"Value of C="<<c;
}

void cal_product()
{
p=a*b*c;
cout<<endl<<"Product of "<<a<<" * "<<b<<" * "<<c<<" = "<<p;
}
};

main()
{

C _c;
_c.set_A();
_c.set_B();
_c.set_C();
_c.disp_A();
_c.disp_B();
_c.disp_C();
_c.cal_product();

return 0;

3. Multilevel Inheritance: In this type of inheritance, a derived class is created from another

derived class.
Syntax:-

Mrs. P.D.Titavekar 13
Object Oriented Programming using c++
class C
{
... .. ...
};
class B:public C
{
... .. ...
};
class A: public B
{
... ... ...
};

1. // C++ program to implement

// Multilevel Inheritance

#include <iostream>

using namespace std;

// base class

class Vehicle {

public:

Vehicle() { cout << "This is a Vehicle\n"; }

};

// first sub_class derived from class vehicle

class fourWheeler : public Vehicle {

public:

fourWheeler()

cout << "Objects with 4 wheels are vehicles\n";

};

// sub class derived from the derived base class fourWheeler

Mrs. P.D.Titavekar 14
Object Oriented Programming using c++
class Car : public fourWheeler {

public:

Car() { cout << "Car has 4 Wheels\n"; }

};

// main function

int main()

// Creating object of sub class will

// invoke the constructor of base classes.

Car obj;

return 0;
}

Output
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels

4. Hierarchical Inheritance: In this type of inheritance, more than one subclass is inherited from a
single base class. i.e. more than one derived class is created from a single base class.

class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}

Mrs. P.D.Titavekar 15
Object Oriented Programming using c++
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}

1. // C++ program to implement


// Hierarchical Inheritance
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// first sub class


class Car : public Vehicle {
};

// second sub class


class Bus : public Vehicle {
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base class.
Car obj1;
Bus obj2;
return 0;
}

Output
This is a Vehicle
This is a Vehicle

5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more than one
type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance.

Mrs. P.D.Titavekar 16
Object Oriented Programming using c++

1. // C++ program for Hybrid Inheritance

#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// base class
class Fare {
public:
Fare() { cout << "Fare of Vehicle\n"; }
};

// first sub class


class Car : public Vehicle {
};

// second sub class


class Bus : public Vehicle, public Fare {
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base class.
Bus obj2;
return 0;
}

Output
This is a Vehicle
Fare of Vehicle

2. // Example:

#include <iostream>
using namespace std;
Mrs. P.D.Titavekar 17
Object Oriented Programming using c++

class A
{
protected:
int a;
public:
void get_a()
{
cout << "Enter the value of 'a' : ";
cin>>a;
}
};

class B : public A
{
protected:
int b;
public:
void get_b()
{
cout << "Enter the value of 'b' : ";
cin>>b;
}
};
class C
{
protected:
int c;
public:
void get_c()
{
cout << "Enter the value of c is : ";
cin>>c;
}
};

class D : public B, public C


{
protected:
int d;
public:
void mul()
{
get_a();
get_b();
get_c();
cout << "Multiplication of a,b,c is : " <<a*b*c;
}
};

int main()
{
D d;
d.mul();
Mrs. P.D.Titavekar 18
Object Oriented Programming using c++
return 0;
}

Dynamic memory allocation using new and delete operators in c++:-


There are times where the data to be entered is allocated at the time of execution. For example, a list
of employees increases as the new employees are hired in the organization and similarly reduces when
a person leaves the organization. This is called managing the memory. So now, let us discuss the
concept of dynamic memory allocation.

Memory allocation

Reserving or providing space to a variable is called memory allocation. For storing the data, memory
allocation can be done in two ways -
o Static allocation or compile-time allocation - Static memory allocation means providing
space for the variable. The size and data type of the variable is known, and it remains constant
throughout the program.
o Dynamic allocation or run-time allocation - The allocation in which memory is allocated
dynamically. In this type of allocation, the exact size of the variable is not known in advance.
Pointers play a major role in dynamic memory allocation.

Dynamically we can allocate storage while the program is in a running state, but variables cannot be
created "on the fly". Thus, there are two criteria for dynamic memory allocation -
o A dynamic space in the memory is needed.
o Storing the address to access the variable from the memory

Similarly, we do memory de-allocation for the variables in the memory.

In C++, memory is divided into two parts -


o Stack - All the variables that are declared inside any function take memory from the stack.
o Heap - It is unused memory in the program that is generally used for dynamic memory
allocation.

Dynamic memory allocation using the new operator

To allocate the space dynamically, the operator new is used. It means creating a request for memory
allocation on the free store. If memory is available, memory is initialized, and the address of that
space is returned to a pointer variable.
Syntax

Pointer_variable = new data_type;

The pointer_varible is of pointer data_type. The data type can be int, float, string, char, etc.

Example

int *m = NULL // Initially we have a NULL pointer

m = new int // memory is requested to the variable

Mrs. P.D.Titavekar 19
Object Oriented Programming using c++
It can be directly declared by putting the following statement in a line -

int *m = new int

Initialize memory

We can also initialize memory using new operator.


For example

int *m = new int(20);

Float *d = new float(21.01);

Allocate a block of memory

We can also use a new operator to allocate a block(array) of a particular data type.

For example

int *arr = new int[10]

Here we have dynamically allocated memory for ten integers which also returns a pointer to the first
element of the array. Hence, arr[0] is the first element and so on.

Note
o The difference between creating a normal array and allocating a block using new normal
arrays is deallocated by the compiler. Whereas the block is created dynamically until the
programmer deletes it or if the program terminates.
o If there is no space in the heap memory, the new request results in a failure throwing an
exception(std::bad_alloc) until we use nonthrow with the new operator. Thus, the best
practice is to first check for the pointer variable.

Delete operator

We delete the allocated space in C++ using the delete operator.

Syntax

delete pointer_variable_name

Example

delete m; // free m that is a variable

delete [] arr; // Release a block of memory

Example to demonstrate dynamic memory allocation


1. // The program will show the use of new and delete
2. #include <iostream>
3. using namespace std;
Mrs. P.D.Titavekar 20
Object Oriented Programming using c++

4. int main ()
5. {
6. // Pointer initialization to null
7. int* m = NULL;
8.
9. // Request memory for the variable
10. // using new operator
11. m = new(nothrow) int;
12. if (!m)
13. cout<< "allocation of memory failed\n";
14. else
15. {
16. // Store value at allocated address
17. *m=29;
18. cout<< "Value of m: " << *m <<endl;
19. }
20. // Request block of memory
21. // using new operator
22. float *f = new float(75.25);
23. cout<< "Value of f: " << *f <<endl;
24. // Request block of memory of size
25. int size = 5;
26. int *arr = new(nothrow) int[size];
27. if (!arr)
28. cout<< "allocation of memory failed\n";
29. else
30. {
31. for (int i = 0; i< size; i++)
32. arr[i] = i+1;
33.
34. cout<< "Value store in block of memory: ";
35. for (int i = 0; i< size; i++)
36. cout<<arr[i] << " ";
37. }
38.
39. // freed the allocated memory
40. delete m;
41. delete f;
42. // freed the block of allocated memory
43. delete[] arr;
44.
45. return 0;
46. }

Output
Value of m: 29
Value of f: 75.25
Mrs. P.D.Titavekar 21
Object Oriented Programming using c++
Value store in block of memory: 1 2 3 4 5

Mrs. P.D.Titavekar 22

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy