0% found this document useful (0 votes)
2 views27 pages

Module 4 Notes

The document discusses inheritance in C++, a key feature of Object-Oriented Programming that allows a derived class to inherit properties and behaviors from a base class. It explains various types of inheritance, including single, multiple, multilevel, hierarchical, and hybrid inheritance, along with access specifiers and the order of constructor and destructor invocation. Additionally, it covers polymorphism, including compile-time and run-time polymorphism, and provides examples of function overloading.
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)
2 views27 pages

Module 4 Notes

The document discusses inheritance in C++, a key feature of Object-Oriented Programming that allows a derived class to inherit properties and behaviors from a base class. It explains various types of inheritance, including single, multiple, multilevel, hierarchical, and hybrid inheritance, along with access specifiers and the order of constructor and destructor invocation. Additionally, it covers polymorphism, including compile-time and run-time polymorphism, and provides examples of function overloading.
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

BACSE104 - Structured and Object-Oriented

Programming

1
BACSE104 - Structured and Object-Oriented Programming
Inheritance
• Inheritance is an Object-Oriented Programming (OOP) feature in C++ that allows one class
(derived/child class) to acquire the properties and behavior of another class (base/parent
class).
• The advantage of Inheritance are,
o Code reusability
o Extensibility
o Method overriding (runtime polymorphism)
o Hierarchical classification
• Syntax of Inheritance:
class Base_class_name {
// members
};
class Derived : access_specifier Base_class_name {
// members
};
• Example:
class Animal {
public:
void eat() {
cout << "Eating\n";
}
};
class Dog : public Animal {
public:
void bark() {
cout << "Barking\n";
}
};

Types of Inheritance

• There are 5 types of Inheritance,


o Single Inheritance
o Multiple Inheritance
o Multilevel Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance

2
BACSE104 - Structured and Object-Oriented Programming
Single Inheritance
• Single inheritance allows a derived class to inherit from only one base class.
• It is the simplest form of inheritance and promotes code reuse and easy maintenance.
• Example: A Student class inheriting properties from Person.
A B
o A → Base class
o B → Derived class
• Example code:
#include<iostream>
using namespace std;
class A
{
public:
void show()
{
cout<<"Function show() in class A"<<endl;
}
};
class B : public A
{
public:
void display()
{
cout<<"Function display() in class B"<<endl;
}
};
int main()
{
B obj;
[Link](); // inherited from class A
[Link](); // member of class B
return 0;
}

3
BACSE104 - Structured and Object-Oriented Programming
Multiple Inheritance
• Multiple inheritance allows a class to inherit from more than one base class.
• It helps combine features from multiple classes into one class.
• Example: A Teaching Assistant may inherit from Student and Teacher.
A B
\ /
C
A and B → Base classes
C → Derived class
• Example code:
#include<iostream>
using namespace std;

class A
{
public:
void show()
{
cout<<"Function show() from class A"<<endl;
}
};

class B
{
public:
void display()
{
cout<<"Function display() from class B"<<endl;
}
};

class C : public A, public B


{
};

int main()
{
C obj;

[Link](); // from class A


[Link](); // from class B

return 0;
}

• Ambiguity issue in multiple inheritance


o If both base classes contain a function with the same name, the compiler cannot
determine which function to call.
o Example of ambiguity
class A
{
4
BACSE104 - Structured and Object-Oriented Programming
public:
void show()
{
cout<<"Show from A"<<endl;
}
};

class B
{
public:
void show()
{
cout<<"Show from B"<<endl;
}
};

class C : public A, public B


{
};

int main()
{
C obj;
[Link](); // ERROR: ambiguous
}
o Solution to Ambiguity: Use the scope resolution operator.
int main()
{
C obj;

obj.A::show(); // calls A's show()


obj.B::show(); // calls B's show()
}

5
BACSE104 - Structured and Object-Oriented Programming
Multilevel Inheritance
• Multilevel inheritance allows a derived class to become a base class for another class.
• This forms a chain of inheritance.
• Example: Person → Employee → Manager
A
|
B
|
C
o A → Base class
o B → Derived from A
o C → Derived from B
• Example Code:
#include<iostream>
using namespace std;

class A
{
public:
void show()
{
cout<<"Function show() from class A"<<endl;
}
};

class B : public A
{
public:
void display()
{
cout<<"Function display() from class B"<<endl;
}
};

class C : public B
{
};

int main()
{
C obj;

[Link](); // inherited from A


[Link](); // inherited from B

return 0;
}

6
BACSE104 - Structured and Object-Oriented Programming
Hierarchical Inheritance
• Hierarchical inheritance allows multiple derived classes to inherit from the same base
class.
• Example: Vehicle → Car, Bike, Bus
• This promotes code reuse among several related classes.
A
/ \
B C

o A → Base class
o B and C → Derived classes
• Example Code:
#include<iostream>
using namespace std;

class A
{
public:
void show()
{
cout<<"Function show() from class A"<<endl;
}
};

class B : public A
{
public:
void display()
{
cout<<"Function display() from class B"<<endl;
}
};
class C : public A
{
public:
void display()
{
cout<<"Function display() from class C"<<endl;
}
};
int main()
{
B obj1;
C obj2;
[Link]();
[Link]();

[Link]();
[Link]();
return 0;
}
7
BACSE104 - Structured and Object-Oriented Programming
Hybrid Inheritance:
• Hybrid inheritance is a combination of two or more inheritance types.

Multipath Inheritance
• Multipath inheritance occurs when there are multiple paths from a base class to a
derived class.
• It usually looks like this:
o Class A is the base.
o Class B and Class C both inherit from Class A.
o Class D inherits from both Class B and Class C.
• A common hybrid case is Diamond Inheritance.
A
/ \
B C
\ /
D
o B and C inherit from A
o D inherits from both B and C
• Problems in Diamond Inheritance
o Data Duplication:
▪ Class D receives two copies of class A, because:
• B inherits A
• C inherits A
• So D contains two A objects.
▪ Solution: Virtual Base Class
▪ Use virtual inheritance so that only one copy of A exists.
A
/ \
virtual virtual
B C
\ /
D
▪ Now D shares only one instance of A.
▪ Example Code with Virtual Inheritance
#include<iostream>
using namespace std;

class A
{
public:
void show()
{
cout<<"Function show() from class A"<<endl;
}
};

// virtual inheritance avoids duplicate A


class B : virtual public A
{
};
8
BACSE104 - Structured and Object-Oriented Programming
class C : virtual public A
{
};

class D : public B, public C


{
};

int main()
{
D obj;

[Link](); // no ambiguity

return 0;
}
o Ambiguity Problem: Calling a function from A becomes ambiguous. (refer
multiple inheritance for the solution to ambiguity problem)

Inheritance Type Structure Key Idea

Single A→B One base, one derived

Multiple A,B → C One class inherits from multiple classes

Multilevel A→B→C Chain of inheritance

Hierarchical A → B,C One base, multiple derived

Hybrid Combination Complex inheritance structures

9
BACSE104 - Structured and Object-Oriented Programming
Access Specifiers in Inheritance
• Access specifiers determine how the base class members are accessible in the derived
class.
• Three access specifiers in C++:
o public
o protected
o private
• When inheritance is declared, we can use:
o class Derived : public Base
o class Derived : protected Base
o class Derived : private Base
• Private members of the base class are never directly accessible in the derived class.
• Public Inheritance:
Base member Becomes in Derived
public public
protected protected
private not accessible
o Represents "is-a" relationship.
o Example:
▪ Car is a Vehicle
▪ Dog is an Animal
o Example code:
#include<iostream>
using namespace std;

class A
{
public:
int x = 10;

protected:
int y = 20;

private:
int z = 30;
};

class B : public A
{
public:
void show()
{
cout << x << endl; // accessible
cout << y << endl; // accessible
// cout << z; // ERROR (private)
}
};

int main()
{
10
BACSE104 - Structured and Object-Oriented Programming
B obj;

cout << obj.x << endl; // allowed


[Link]();
}
• Protected Inheritance:
o Members cannot be accessed outside the derived class.
Base member Becomes in Derived
public protected
protected protected
private not accessible
o Example code:
#include<iostream>
using namespace std;

class A
{
public:
int x = 10;
};

class B : protected A
{
public:
void show()
{
cout << x << endl; // accessible inside
}
};

int main()
{
B obj;

// cout << obj.x; // ERROR

[Link]();
}
• Private Inheritance:
o Base class members become completely hidden from outside access.
Base member Becomes in Derived
public private
protected private
private not accessible

o Example code:
#include<iostream>
using namespace std;
11
BACSE104 - Structured and Object-Oriented Programming
class A
{
public:
int x = 10;
};

class B : private A
{
public:
void display()
{
cout << x << endl; // accessible inside
}
};

int main()
{
B obj;

// cout << obj.x; // ERROR


[Link]();
}

12
BACSE104 - Structured and Object-Oriented Programming
Constructors in Inheritance
• When an object of a derived class is created: Base class constructor executes first, then
derived class constructor.
• Derived class depends on base class initialization.
• Order of Invocation: Base Constructor → Derived Constructor
• Example:
#include<iostream>
using namespace std;

class A
{
public:
A()
{
cout<<"Constructor of A"<<endl;
}
};

class B : public A
{
public:
B()
{
cout<<"Constructor of B"<<endl;
}
};

int main()
{
B obj;
}
Output:
Constructor of A
Constructor of B
• Invoking Base Constructor from Derived Constructor
o If the base class has parameterized constructor, the derived class must explicitly
call it.
o Syntax:
Derived_class_name() : Base_class_name(arguments)
{
}
o Example code:
#include<iostream>
using namespace std;

class A
{
public:
int x;

A(int a)
13
BACSE104 - Structured and Object-Oriented Programming
{
x = a;
}
};

class B : public A
{
public:
int y;

B(int a, int b) : A(a) // calling base constructor


{
y = b;
}

void display()
{
cout<<x<<" "<<y<<endl;
}
};

int main()
{
B obj(10,20);
[Link]();
}

14
BACSE104 - Structured and Object-Oriented Programming
Destructor in Inheritance
• Destructor execution order is reverse of constructor order.
• Order of invocation:
o Derived Destructor → Base Destructor
o Derived resources must be released before base resources.
• Example code:
#include<iostream>
using namespace std;

class A
{
public:
~A()
{
cout<<"Destructor of A"<<endl;
}
};

class B : public A
{
public:
~B()
{
cout<<"Destructor of B"<<endl;
}
};

int main()
{
B obj;
}

Output:
Destructor of B
Destructor of A

• Virtual Destructors:
o Virtual destructors are used when deleting derived objects through base class
pointers.
o Without virtual destructor → only base destructor runs, causing resource
leak.
o Example code:
#include<iostream>
using namespace std;

class A
{
public:
~A()
{
cout<<"Destructor of A"<<endl;
15
BACSE104 - Structured and Object-Oriented Programming
}
};

class B : public A
{
public:
~B()
{
cout<<"Destructor of B"<<endl;
}
};

int main()
{
A* ptr = new B();

delete ptr; // problem


}
Output:
Destructor of A
// Derived destructor not called.

o Solution: Virtual Destructor - Make base destructor virtual.


o Example code:
#include<iostream>
using namespace std;

class A
{
public:
virtual ~A()
{
cout<<"Destructor of A"<<endl;
}
};
class B : public A
{
public:
~B()
{
cout<<"Destructor of B"<<endl;
}
};
int main()
{
A* ptr = new B();
delete ptr;
}
Output:
Destructor of B
Destructor of A
16
BACSE104 - Structured and Object-Oriented Programming
Polymorphism

• In C++, polymorphism allows the same function name or operator to perform different
tasks depending on the context.

• It improves: Code reusability, Flexibility, Readability

• Polymorphism is mainly classified into two types,


o Compile-time or Static Polymorphism
o Run-time or Dynamic Polymorphism

• Compile-time Polymorphism:
o The compiler decides which function to call during compilation.
o Examples of compile-time polymorphism.
▪ Function Overloading
▪ Operator Overloading

• Runtime Polymorphism:
o Runtime Polymorphism is achieved using Function Overriding (with
inheritance).
o The decision about which function to execute happens at runtime.
Base pointer -> Derived object

17
BACSE104 - Structured and Object-Oriented Programming
Function Overloading

• Function overloading means multiple functions having the same name but different
parameter lists.
• Difference in functions can be in:
o Number of parameters
o Type of parameters
o Order of parameters
• The compiler decides which function to call based on function signature.
• Changing only the return type is not enough to overload a function; the compiler needs
the parameters to be different to distinguish which version to call.
• Example code:
#include<iostream>
using namespace std;

class A
{
public:

void show(int x)
{
cout<<"Integer: "<<x<<endl;
}

void show(double x)
{
cout<<"Double: "<<x<<endl;
}

void show(int x, int y)


{
cout<<"Sum: "<<x+y<<endl;
}
};

int main()
{
A obj;

[Link](10);
[Link](5.5);
[Link](5,6);
}
• Function Overloading using Default Arguments: Default arguments can also produce
multiple behaviors using the same function.
o Example code:
#include<iostream>
using namespace std;

class A
18
BACSE104 - Structured and Object-Oriented Programming
{
public:
void show()
{
cout<<”In show”;
}

//below show method is invoked if there are one or two integer parameters
void show(int x, int y = 0)
{
cout<<"Result: "<<x + y<<endl;
}

//below show method will conflict with show(int x, int y = 0), (ambiguous)
/*void show(int x)
{
cout<<"Result: "<<x + y<<endl;
}*/

};

int main()
{
A obj;

[Link](10); // y uses default value


[Link](10,20); //both arguments provided
}

19
BACSE104 - Structured and Object-Oriented Programming
Operator Overloading

• Operator overloading allows operators to be redefined for user-defined data types


(classes).
• Example:
int a, b;
a+b //a and b are primitive types, so a+b gives the sum of a and b

obj1 + obj2
//here obj1 and obj2 are objects, + can be overloaded to perform custom
operations
• Operator overloading helps to:
o Make code more readable
o Use natural syntax
o Allow objects to behave like built-in types
• Example:
o complex1 + complex2
o instead of add(complex1, complex2)
• Syntax:
return_type operator symbol(parameters)
{
// logic
}
• Example: Complex operator+(Complex obj);
• Example Overloading + Operator:
#include<iostream>
using namespace std;

class A
{
public:

int x;

A(int a)
{
x = a;
}

// Overloading + operator
A operator+(A obj)
{
A temp(0);

temp.x = x + obj.x; // add values of two objects

return temp;
}

20
BACSE104 - Structured and Object-Oriented Programming
void display()
{
cout<<x<<endl;
}
};

int main()
{
A obj1(10);
A obj2(20);

A obj3 = obj1 + obj2; // calls operator+

[Link]();
}
• Example Overloading [] Operator (Array Index Operator)
#include<iostream>
using namespace std;

class A
{
int arr[5];

public:

A()
{
for(int i=0;i<5;i++)
arr[i] = i * 10;
}

// overload [] operator
int operator[](int index)
{
return arr[index];
}
};

int main()
{
A obj;

cout<<obj[2]; // accesses arr[2]


}
• Example Overloading ++ Prefix Operator:
class A
{
public:
int x;

A(int a)
21
BACSE104 - Structured and Object-Oriented Programming
{
x = a;
}

// overloading prefix ++
A operator++()
{
++x; // increment first
return *this;
}
};
• Example Overloading ++ Postfix Operator:
class A
{
public:
int x;

A(int a)
{
x = a;
}

// postfix ++
A operator++(int)
{
A temp = *this;

x++; // increment after

return temp;
}
};

22
BACSE104 - Structured and Object-Oriented Programming
Function Overriding

• Function overriding occurs when a derived class provides its own implementation of a
function already defined in the base class.
• Conditions for overriding,
o Same function name
o Same parameters
o Inheritance required
• Used when derived class needs a different implementation of a base class function.
• Example scenario:
Shape -> area()
Circle -> area()
Rectangle -> area()
o Each class overrides the base implementation. (Here Shape is the base class,
Circle and Rectangle are the derived classes)
Case Behavior
Without virtual Early binding (compile time)
With virtual Late binding (runtime polymorphism)
• Syntax:
class Base
{
public:
void show();
};

class Derived : public Base


{
public:
void show(); // overriding
};
• Example code: (Without virtual function - Early binding (compile time))
#include<iostream>
using namespace std;

class A
{
public:
//base class show() method
void show()
{
cout<<"Show function of class A"<<endl;
}
};

class B : public A
{
public:

void show() // overrides A's show()


23
BACSE104 - Structured and Object-Oriented Programming
{
cout<<"Show function of class B"<<endl;
}
};

int main()
{
B obj;
[Link](); // calls derived version
A obj1;
[Link](); //calls base version
A* aobj = &obj;
aobj->show(); // calls base version

}
• Example code: (With virtual function - Late binding (runtime time))
#include<iostream>
using namespace std;

class A
{
public:
//base class show() method
virtual void show()
{
cout<<"Show function of class A"<<endl;
}
};

class B : public A
{
public:

void show() // overrides A's show()


{
cout<<"Show function of class B"<<endl;
}
};

int main()
{
B obj;
[Link](); // calls derived version
A obj1;
[Link](); //calls base version
A* aobj = &obj;
aobj->show(); // calls derived version (runtime polymorphism)

24
BACSE104 - Structured and Object-Oriented Programming
Virtual Function
• A virtual function is a member function of a class declared using the keyword virtual
that allows runtime polymorphism.
• It ensures that the correct function is called based on the object type at runtime, even
when using a base class pointer.
• Virtual functions are used when:
o base class pointer refers to derived class object
o runtime polymorphism is required
• Example scenario:
Shape -> area()
Circle -> area()
Rectangle -> area()
The correct area() should run depending on the object.
• Syntax:
class Base
{
public:
virtual void show();
};
class Derived : public Base
{
public:
void show();
};
• Example code:
#include<iostream>
using namespace std;
class A
{
public:
virtual void show()
{
cout<<"Show from class A"<<endl;
}
};
class B : public A
{
public:
void show()
{
cout<<"Show from class B"<<endl;
}
};
int main()
{
A* ptr;
B obj;
ptr = &obj;
ptr->show(); // runtime polymorphism
}
25
BACSE104 - Structured and Object-Oriented Programming
Pure Virtual Function

• A pure virtual function is a virtual function that has no implementation in the base
class.
• It forces derived classes to provide their own implementation.
• Syntax:
virtual return_type function_name() = 0;
The = 0 makes it pure virtual.
• Example: virtual void show() = 0;
• Difference Between Virtual and Pure Virtual Function
Feature Virtual Function Pure Virtual Function
Implementation in base class Yes No
Can create object of base class Yes No
Derived class must override Optional Mandatory
Used for Runtime polymorphism Abstract class design
• Pure virtual functions are used when,
o A base class should only define an interface
o Derived classes must implement their own behavior
• Example code:
#include<iostream>
using namespace std;

class A
{
public:

// pure virtual function


virtual void show() = 0;
};

class B : public A
{
public:

void show()
{
cout<<"Implementation of show() in class B"<<endl;
}
};

int main()
{
B obj;

[Link]();
}

26
BACSE104 - Structured and Object-Oriented Programming
Abstract class

• An abstract class is a class that contains at least one pure virtual function.
• Because of the pure virtual function, objects of abstract classes cannot be created.
• Characteristics of Abstract Class,
o Contains at least one pure virtual function and zero or more functions with
implementation.
o Objects cannot be created
o Used as base class
o Derived class must implement pure virtual functions else derived class will
become abstract class.
• Syntax:
class ClassName
{
public:

virtual void functionName() = 0;

};
• Example code:
#include<iostream>
using namespace std;

class A
{
public:

// pure virtual function


virtual void display() = 0;
};

class B : public A
{
public:

void display()
{
cout<<"Display function implemented in class B"<<endl;
}
};

int main()
{
// A obj; // ERROR: cannot create object of abstract class

B obj;

[Link]();
}

27
BACSE104 - Structured and Object-Oriented Programming

You might also like