0% found this document useful (0 votes)
3 views50 pages

OOP With C - (Module 3) (1) ..

The document provides an overview of inheritance in C++, explaining concepts such as derived classes, types of inheritance (single, multilevel, multiple, hybrid, and hierarchical), and the visibility modes of inherited members. It also covers function overriding, abstract classes, pointers, and memory management, including the use of the new and delete operators for dynamic memory allocation. The document illustrates these concepts with code examples demonstrating how inheritance and memory management work in practice.

Uploaded by

ff974500
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views50 pages

OOP With C - (Module 3) (1) ..

The document provides an overview of inheritance in C++, explaining concepts such as derived classes, types of inheritance (single, multilevel, multiple, hybrid, and hierarchical), and the visibility modes of inherited members. It also covers function overriding, abstract classes, pointers, and memory management, including the use of the new and delete operators for dynamic memory allocation. The document illustrates these concepts with code examples demonstrating how inheritance and memory management work in practice.

Uploaded by

ff974500
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module 3

Inheritance
• In C++, inheritance is a process in which one object acquires all the
properties and behaviors of its parent object automatically.
• In such way, you can reuse, extend or modify the attributes and behaviors
which are defined in other class.
• In C++, the class which inherits the members of another classis called
derived class and the class whose members are inherited is called base
class.
• The derived class is the specialized class for the base class.
• Code reusability: Now you can reuse the members of your parent class. So,
there is no need to define the member again. So less code is required in
the class.
Derived Classes
• A Derived class is defined as the class derived from the base class.
• derived_class_name: It is the name of the derived class.
• visibility mode: The visibility mode specifies whether the features of
the base class are publicly inherited or privately inherited. It can be
public or private.
• base_class_name: It is the name of the base class.
• When the base class is privately inherited by the derived class, public
members of the base class becomes the private members of the
derived class. Therefore, the public members of the base class are not
accessible by the objects of the derived class only by the member
functions of the derived class.
• 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 base class.
Types Of Inheritance
#include <iostream> using
namespace std; class
Account {
public:
float salary = 60000;
• Single inheritance is };
defined as the inheritance class Programmer: public Account {
in which a derived class is public:
inherited from the only float bonus = 5000;
one base class. };
• Where 'A' is the base int main(void) {
Programmer p1;
class, and 'B' is the cout<<"Salary: "<<[Link]<<endl;
derived class. cout<<"Bonus: "<<[Link]<<endl;
return 0;
}
#include <iostream> using
namespace std; class A
{
int a = 4;
int b = 5;
public:
int mul()
{ int c = a*b;
return c;
}
};
class B : private A
{
public:
void display()
{
int result = mul();
std::cout <<"Multiplication of a and b is : "<<result<< std::endl;
}
};
int main()
{
B b;
[Link]();
return 0;
}
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking..."<<endl;
}
• Multilevel Inheritance is a };
process of deriving a class class BabyDog: public Dog
from another derived class. {
public:
void weep() {
cout<<"Weeping...";
}
#include <iostream> };
using namespace std; int main(void) {
class Animal { BabyDog d1;
public: [Link]();
void eat() [Link]();
{ [Link]();
cout<<"Eating..."<<endl; return 0;
} }
};
• Multiple inheritance is the process of deriving a new class that
inherits the attributes from two or more classes.
#include <iostream>
using namespace std; class C : public A,public B
class A {
{ public:
protected: void display()
int a; {
public: std::cout << "The value of a is : " <<a<< std::endl;
void get_a(int n) std::cout << "The value of b is : " <<b<< std::endl;
{ cout<<"Addition of a and b is : "<<a+b;
a = n; }
} };
}; int main()
class B {
{ C c;
protected: c.get_a(10);
int b; c.get_b(20);
public: [Link]();
void get_b(int n)
{ return 0;
b = n; }
}
};
• Hybrid inheritance is a combination of more than one type of
inheritance.
#include <iostream> class D : public B, public C
using namespace std; {
class A { protected:
protected: int d;
int a; public:
public: void mul()
void get_a() {
{ cout << "Enter the value of 'a' : " << endl; get_a();
cin>>a; get_b();
} }; get_c();
class B : public A { cout << "Multiplication of a,b,c is : " <<a*b*c;
protected: }
int b; };
public: int main()
void get_b() {
{ cout << "Enter the value of 'b' : " << endl; D d;
cin>>b; [Link]();
} }; return 0;
class C }
{ protected: int c; public:
void get_c()
{ cout << "Enter the value of c is : " << endl;
cin>>c;
} };
• Hierarchical inheritance is defined as class A
{
the process of deriving more than // body of the class
one class from a base class. A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
#include <iostream>
using namespace std;
class Shape
{public:
int main()
int a;
{ Rectangle r;
int b;
Triangle t;
void get_data(int n,int m)
int length,breadth,base,height;
{ a= n;
cout << "Enter the length and breadth of a rectangle: " << endl;
b=m;
cin>>length>>breadth;
} };
r.get_data(length,breadth);
class Rectangle : public Shape
int m = r.rect_area();
{ public:
cout << "Area of the rectangle is : " <<m<< endl;
int rect_area()
cout << "Enter the base and height of the triangle: " << endl;
{ int result = a*b;
cin>>base>>height;
return result;
t.get_data(base,height);
} };
float n = t.triangle_area();
class Triangle : public Shape
cout <<"Area of the triangle is : " << n<<endl;
{ public:
return 0;
int triangle_area()
}
{ float result = 0.5*a*b;
return result;
} };
Constructor/ destructor in Inheritance
#include <iostream> class child: public parent
using namespace std; {
class parent public:
child()
{
{
public: cout<<"child class constructor"<<endl;
parent() }
~child()
{ {
cout<<"parent class constructor"<<endl; cout<<"child class destructor"<<endl;
}
} };
~parent() int main() {
{ child c1;
return 0;
cout<<"parent class destructor"<<endl; }
}
};
#include <iostream>
using namespace std;
int main() {
// Base class Student s;
class Person { [Link]("Suraj"); // setName is public
protected: [Link]();
string name; // Protected member return 0;
}
public:
void setName(string n) {
name = n;
}
};

// Derived class
class Student : public Person {
public:
void display() {
cout << "Student Name: " << name << endl;
}
};
The way those members are inherited depends on the type of inheritance:
•public
•protected
•private

Base Class Member Type Public Inheritance Protected Inheritance Private Inheritance
public public protected private
protected protected protected private
private Not inherited Not inherited Not inherited
Accessible from outside
#include <iostream>
using namespace std;
class Base {
public:
int pub = 1;
protected:
int prot = 2;
private:
int priv = 3;
};
class PublicDerived : public Base {
public:
void display() {
cout << "Public: " << pub << endl; // OK
cout << "Protected: " << prot << endl; // OK
// cout << "Private: " << priv << endl; // Error
}
};
class ProtectedDerived : protected Base {
public:
void display() {
cout << "Public becomes Protected: " << pub << endl; // OK
cout << "Protected: " << prot << endl; // OK
}
};
class PrivateDerived : private Base {
public:
void display() {
cout << "Public becomes Private: " << pub << endl; // OK
cout << "Protected becomes Private: " << prot << endl; // OK
}
};

int main() {
PublicDerived obj1;
[Link]();
cout << [Link] << endl; // OK: remains public Public: 1
Protected: 2
ProtectedDerived obj2; Public becomes Protected: 1
[Link](); Protected: 2
// cout << [Link] << endl; // Error: now protected Public becomes Private: 1
Protected becomes Private: 2
PrivateDerived obj3; 1
[Link]();
// cout << [Link] << endl; // Error: now private

return 0;
}
Function overriding
• Function overriding occurs when a derived class has a member
function with the same name, return type, and parameters as a
virtual function in the base class
#include <iostream>
using namespace std; int main() {
Animal* a; // Base class pointer
// Base class Dog d; // Derived class object
class Animal { a = &d;
public:
virtual void makeSound() { a->makeSound(); // Calls Dog::makeSound because
cout << "Animal makes a sound" << endl; of virtual function
} return 0;
}; }
// Derived class
class Dog : public Animal {
public:
void makeSound() override { // overrides
Animal::makeSound
cout << "Dog barks" << endl;
}
};
• An abstract class in C++ is a class that cannot be instantiated and is
typically used as a base class. It contains at least one pure virtual
function.
• A pure virtual function is a function that has no definition in the base
class and must be overridden in derived classes.
#include <iostream> // Another Derived Class
using namespace std; class Cat : public Animal {
public:
// Abstract Base Class void makeSound() override {
class Animal { cout << "Cat meows" << endl;
public: }
virtual void makeSound() = 0; // Pure };
virtual function
int main() {
void breathe() { // Animal a; // Error: Cannot instantiate
cout << "Animal breathes" << endl; abstract class
}
}; Animal* d = new Dog();
Animal* c = new Cat();
// Derived Class
class Dog : public Animal { d->makeSound(); // Output: Dog barks
public: c->makeSound(); // Output: Cat meows
void makeSound() override {
cout << "Dog barks" << endl; delete d;
} delete c;
};
return 0;
}
#include <iostream>

Pointers using namespace std;

int main() {
int var = 10;
• A pointer is a special variable that // declare pointer and store address of x
holds the memory address of int* ptr = &var;
another variable, rather than storing
a direct value itself. // print value and address
• Pointers allow programs to access cout << "Value of x: " << var << endl;
and manipulate data in memory cout << "Address of x: " << &var << endl;
efficiently, making them a key cout << "Value stored in pointer ptr: " << ptr << endl;
feature for system-level cout << "Value pointed to by ptr: " << *ptr << endl;
programming and dynamic memory
management. return 0;
}
• When we access a pointer directly, Value of x: 10

we get the address it holds not the Address of x: 0x7fffa0757dd4

actual data stored at that location. Value stored in pointer ptr:


0x7fffa0757dd4

Value pointed to by ptr: 10


Function Pointer in C++
● The function pointer is used to
point functions, similarly, the
pointers are used to point
variables.
● It is utilized to save a function's
address.
● The function pointer is either used
to call the function or it can be
sent as an argument to another
function.
Memory Management
• In C++, stack memory is automatically allocated for variables at compile
time and has a fixed size. For greater control and flexibility, dynamic
memory allocation on the heap is used, allowing manual allocation with
new and deallocation with delete.
• It allows the program to request memory from the heap at runtime using
the new operator and release it using the delete operator. This is useful
when the size of required memory isn’t known at compile time, such as
for variable-sized arrays or dynamic data structures like linked lists and
trees.
#include <iostream>

new operator #include <memory>


using namespace std;

int main() {
● The new operator in C++ allocates
// Declared a pointer to store
memory from the Free Store (a // the address of the allocated
memory
portion of the heap). If enough int *nptr;
memory is available, it initializes
// Allocate and initialize memory
the memory with a default value nptr = new int(6);
based on its type and returns the
// Print the value
address of the allocated memory cout << *nptr << endl;

// Print the address of memory


// block
cout << nptr;
return 0;
}
#include <iostream>
new operator with array #include <memory>
using namespace std;

int main() {

// Declared a pointer to store


// the address of the allocated
memory
int *nptr;

// Allocate and initialize array of


// integer with 5 elements
nptr = new int[5]{1, 2, 3, 4, 5};

// Print array
for (int i = 0; i < 5; i++)
cout << nptr[i] << " ";
return 0;
}
delete Operator
In C++, delete operator is used to release dynamically allocated memory. It
deallocates memory that was previously allocated with new.

Syntax
delete ptr;

where, ptr is the pointer to the dynamically allocated memory.


To free the dynamically allocated array pointed by pointer variable, use the
following form of delete:
delete[] arr;
#include <iostream> // Allocate an array
using namespace std; ptr = new int[3];
int main() { ptr[2] = 11;
int *ptr = NULL; ptr[1] = 22;
ptr[0] = 33;
// Request memory for integer variable cout << "Array: ";
// using new operator for (int i = 0; i < 3; i++)
ptr = new int(10); cout << ptr[i] << " ";
if (!ptr) {
cout << "allocation of memory failed"; // Deallocate when done
exit(0); delete[] ptr;
}
return 0;
cout << "Value of *p: " << *ptr << endl; }
// Free the value once it is used
delete ptr;
Base Class Pointer Pointing to Derived Class Object
● A derived class is a class that takes some properties from its base class.
● It is true that a pointer of one class can point to another class, but classes must be a base and
derived class, then it is possible.
● To access the variable of the base class, a base class pointer will be used.
● So, a pointer is a type of base class, and it can access all, public function and variables of the
base class since the pointer is of the base class, this is known as a binding pointer.
● In this pointer base class is owned by the base class but points to the derived class object.
● The same works with derived class pointer, values are changed.
// C++ program to Demonstrate the implementation of the base class pointer pointing to derived class
#include <iostream>
using namespace std;
class BaseClass {
public:
int var_base;

// Function to display the base class members


void display()
{ cout << "Displaying Base class" << " variable var_base: " << var_base << endl; }
};
class DerivedClass : public BaseClass {
public:
int var_derived;
// Function to display the base and derived class members
void display()
{
cout << "Displaying Base class"<< "variable var_base: " << var_base << endl;
cout << "Displaying Derived "<< " class variable var_derived: " << var_derived << endl;
}
};
int main()
{ // Pointer to base class
BaseClass* base_class_pointer;
BaseClass obj_base;
DerivedClass obj_derived;

base_class_pointer = &obj_derived;
base_class_pointer->var_base = 34;

// If you uncomment this line of code this will cause the following error As base-class pointer cannot
// access the derived class variable. base_class_pointer->var_derived = 98;
// output: error: ‘class BaseClass’ has no member named ‘var_derived’

// Calling base class member function


base_class_pointer->display();
base_class_pointer->var_base = 3400;
base_class_pointer->display();
DerivedClass* derived_class_pointer;
derived_class_pointer = &obj_derived;
derived_class_pointer->var_base = 9448;
derived_class_pointer->var_derived = 98;
derived_class_pointer->display();
return 0;
}
Polymorphism
• The term "Polymorphism" is the combination of "poly"
+ "morphs" which means many forms. It is a greek
word.
Virtual Function in C++
A virtual function (also known as virtual methods) is a member function that is declared
within a base class and is re-defined (overridden) by a derived class. When you refer to a
derived class object using a pointer or a reference to the base class, you can call a virtual
function for that object and execute the derived class's version of the method.

● Virtual functions ensure that the correct function is called for an object, regardless of

the type of reference (or pointer) used for the function call.
● They are mainly used to achieve Runtime polymorphism.

● Functions are declared with a virtual keyword in a base class.

● The resolving of a function call is done at runtime.


#include <iostream> int main() {
using namespace std; Base* basePtr;
class Base { Derived derivedObj;
public: // Base class pointer pointing
// Virtual function // to derived class object
virtual void display() { basePtr = &derivedObj;
cout << "Base class display" << endl; // Calling the virtual function
} basePtr->display();
}; return 0;
class Derived : public Base { }
public:

// Overriding the virtual


// function in the derived class
void display() {
cout << "Derived class display" << endl;
}
};
Pure Virtual Function
• A virtual function is called a pure virtual function if it does not have any
implementation and is assigned = 0. A class that contains a pure virtual
function is called an abstract class.
• An abstract class is a class that cannot be used to create objects directly.
It is meant to be a base class that provides a common interface but
doesn't define full behavior.
• A class becomes abstract if it has at least one pure virtual function.
#include <iostream>
using namespace std;
class Base {
public:
// Pure virtual function
virtual void display() = 0;
};

class Derived : public Base {


public:
void display() override {
cout << "Derived class display" << endl;
}
};

int main() {
Base* basePtr;
Derived derivedObj;
basePtr = &derivedObj;
basePtr->display();
return 0;
}
#include <iostream>
using namespace std;
class base {
public:
virtual void print() { int main() {
cout << "print base " base* bptr;
"class\n"; derived d;
} bptr = &d;
// Virtual function,
void show() { // binded at runtime
cout << "show base class\n"; bptr->print();
} // Non-virtual function,
}; // binded at compile time
class derived : public base { bptr->show();
public: return 0;
void print() { }
cout << "print derived class\n";
}

void show() {
cout << "show derived class\n";
}
};
int main() {

base* p;
derived obj1;
#include <iostream>
p = &obj1;
using namespace std;
// Early binding because fun1() is non-virtual
class base {
// in base
public:
p->fun_1();
void fun_1() { cout << "base-1\n"; }
virtual void fun_2() { cout << "base-2\n"; }
// Late binding (RTP)
virtual void fun_3() { cout << "base-3\n"; }
p->fun_2();
virtual void fun_4() { cout << "base-4\n"; }
};
// Late binding (RTP)
p->fun_3();
class derived : public base {
public:
// Late binding (RTP)
void fun_1() { cout << "derived-1\n"; }
p->fun_4();
void fun_2() { cout << "derived-2\n"; }
void fun_4(int x) { cout << "derived-4\n"; }
// Early binding but this function call is
};
// illegal (produces error) because pointer
// is of base type and function is of
// derived class
// p->fun_4(5);

return 0;
}
Rules for Virtual Functions
The rules for the virtual functions in C++ are as follows:

1. Virtual functions cannot be static.

2. A virtual function can be a friend function of another class.

3. Virtual functions should be accessed using a pointer or reference of base class type to achieve runtime

polymorphism.
4. The prototype of virtual functions should be the same in the base as well as the derived class.

5. They are always defined in the base class and overridden in a derived class. It is not mandatory for the

derived class to override (or re-define the virtual function), in that case, the base class version of the
function is used.
6. A class may have a virtual destructor, but it cannot have a virtual constructor.
Virtual Destructor
• Deleting a derived class object using a pointer of base class type that
has a non-virtual destructor results in undefined behavior. To correct
this situation, the base class should be defined with a virtual destructor.
#include <iostream>
using namespace std;
class base {
public:
base()
{ cout << "Constructing base\n"; }
virtual ~base()
{ cout << "Destructing base\n"; }
};
class derived : public base {
public:
derived()
{ cout << "Constructing derived\n"; }
~derived()
{ cout << "Destructing derived\n"; }
};
int main()
{
derived *d = new derived();
base *b = d;
delete b;
getchar();
return 0;
}
Friend Class
• A friend class can access private and protected members of other classes
in which it is declared as a friend.
• It is sometimes useful to allow a particular class to access private and
protected members of other classes. Remember one thing, Friendship is
not mutual. If class A is a friend of B, then B doesn't become a friend of A
automatically.
• We can declare a friend class in C++ by using the friend keyword.
#include <iostream> // class GFG is declared as a friend
using namespace std; // inside class Geeks, therefore
// Class GFG can access private members of class Geeks.
class Geeks { class GFG {
private: public:
int private_variable; void display(Geeks& t) {
cout << "The value of Private Variable = "
protected: << t.private_variable << endl;
int protected_variable; cout << "The value of Protected Variable = "
<< t.protected_variable;
public: }
Geeks() { };
private_variable = 10;
protected_variable = 99; int main() {
} Geeks g;
GFG fri;
// friend class declaration [Link](g);
friend class GFG; return 0;
}; }

Output
The value of Private Variable = 10
The value of Protected Variable = 99
Friend Function
Like friend classes, a friend function can be granted special access to private and protected
members of a class in C++. They are not the member functions of the class but can access
and manipulate the private and protected members of that class for they are declared as
friends.

Global Function as Friend Function


The keyword “friend” is placed only in the function declaration of the friend function and
not in the function definition or call.

Member Function of Another Class as Friend Function

We can also declare a member function of another class as a friend function in C++.
Forward declaration of the class is needed if we want to make a member function of
another class a friend inside that class.
#include <iostream>
using namespace std;

class base { // friend function definition


private: void friendFunction(base& obj) {
int private_variable; cout << "Private Variable: " << obj.private_variable << endl;
cout << "Protected Variable: " << obj.protected_variable;
protected: }
int protected_variable;
int main() {
public: base object1;
base() { friendFunction(object1);
private_variable = 10; return 0;
protected_variable = 99; }
}

// Friend function declaration


friend void friendFunction(base& obj);
};
#include <iostream>
using namespace std;
class base;

// Another class in which function is declared


class GFG { // Friend function definition
public: void GFG::GFG_Function(base& obj) {
void GFG_Function(base& obj); cout << "Private Variable: " <<
}; obj.private_variable
<< endl;
// Base class declare a frined function of another class cout << "Protected Variable: " <<
class base { obj.protected_variable;
private: }
int private_variable;
protected: int main() {
int protected_variable; base object1;
public: GFG object2;
base() { object2.GFG_Function(object1);
private_variable = 10;
protected_variable = 99; return 0;
} }

// Friend function declaration


friend void GFG::GFG_Function(base&);
};

You might also like