[go: up one dir, main page]

0% found this document useful (0 votes)
133 views96 pages

Unit 4

This document contains a course syllabus for Problem Solving using C++ (22CS101). It outlines the course objectives, prerequisites, syllabus breakdown into 5 units, course outcomes, and mapping of course outcomes to program outcomes. The syllabus provides details of each unit's topics and number of periods. It also lists prescribed textbooks and references.
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)
133 views96 pages

Unit 4

This document contains a course syllabus for Problem Solving using C++ (22CS101). It outlines the course objectives, prerequisites, syllabus breakdown into 5 units, course outcomes, and mapping of course outcomes to program outcomes. The syllabus provides details of each unit's topics and number of periods. It also lists prescribed textbooks and references.
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
You are on page 1/ 96

Please read this disclaimer before proceeding:

This document is confidential and intended solely for the educational purpose of RMK
Group of Educational Institutions. If you have received this document through email in
error, please notify the system manager. This document contains proprietary information
and is intended only to the respective group / learning community as intended. If you
are not the addressee you should not disseminate, distribute or copy through e-mail.
Please notify the sender immediately by e-mail if you have received this document by
mistake and delete this document from your system. If you are not the intended
recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contents of this information is strictly prohibited.
22CS101
Problem Solving using C++

Department :Computer Science & Engineering


Batch / Year : 2022 – 2026 / I
Created by : Subject Handling Faculties
Date : 07.11.2022
1. Contents
S. No. Contents

1 Contents

2 Course Objectives

3 Prerequisites

4 Syllabus

5 Course Outcomes

6 CO-PO Mapping

7 Lecture Plan

8 Activity Based Learning

9 Lecture Notes

10 Assignments

11 Part- A Questions & Answers

12 Part-B Questions

13 Supportive Online Courses

14 Real Time Applications

15 Content beyond the Syllabus

16 Assessment Schedule

17 Prescribed Text books & Reference Books

18 Mini Project Suggestions


Unit - 4 Content

Chapter No. Contents

4.1 Operator Overloading

4.2 Overloading Using Friend functions

4.3 Inheritance

4.4 Types of inheritance

5.5 Virtual Base Class

4.6 Abstract Class

4.7 Constructors in Derived Classes

4.8 member class

4.9 Nesting of classes.

4.10 Pointer to objects

4.11 this pointer

4.12 Pointer to derived Class

4.13 Virtual functions

4.14 Pure Virtual Functions

4.15 Polymorphism
2. Course Objectives
❖ To learn problem solving and programming fundamentals.

❖ To gain knowledge on pointers and functions.

❖ To apply the principles of object orientated programming.

❖ To understand operator overloading, inheritance and polymorphism.

❖ To use the functionalities of I/O operations, files build C++ programs

using exceptions.
3. Prerequisites

22CS101
Problem Solving Using C++

Fundamentals of
Programming

Logical Thinking

Fundamentals of
Mathematics
4. Syllabus
PROBLEM SOLVING USING C++ L T P C
22CS101 (Lab Integrated) 3 0 2 4
OBJECTIVES:
To learn programming fundamentals in C.
To gain knowledge on pointers and functions.
To apply the principles of classes and objects
To develop a C++ application with object oriented concepts.
To use the functionalities of I/O operations, files build C++ programs using exceptions.
UNIT I PROGRAMMING FUNDAMENTALS 15

Computational thinking for Problem solving – Algorithmic thinking for problem Solving- Building
Blocks - Problem Solving and Decomposition –Dealing with Error – Evaluation. Overview of C –
Data types – Identifiers – Variables – Storage Class Specifiers – Constants – Operators -
Expressions – Statements – Arrays and Strings – Single-Dimensional – Two-
Dimensional Arrays – Arrays of Strings – Multidimensional Arrays.

UNIT II POINTERS AND FUNCTIONS 15

Pointers -Variables – Operators – Expressions – Pointers and Arrays – Functions - Scope Rules –
Function Arguments – return Statement – Recursion – Structures – Unions – Enumerations.

UNIT III CLASSES AND OBJECTS 15

Concepts of Object Oriented Programming – Benefits of OOP – Simple C++ program - Classes and
Objects - Member functions - Nesting of member functions - Private member functions - Memory
Allocation for Objects - Static Data Members - Static Member functions - Array of Objects - Objects
as function arguments - Returning objects - friend functions – Const Member functions -
Constructors – Destructors

UNIT IV OPERATOR OVERLOADING , INHERITANCE AND POLYMORPHISM 15

Operator Overloading - Overloading Using Friend functions – Inheritance – Types of inheritance –


Virtual Base Class - Abstract Class – Constructors in Derived Classes - member class: nesting of
classes. Pointer to objects – this pointer- Pointer to derived Class - Virtual functions – Pure Virtual
Functions – Polymorphism

UNIT V I/O, FILES AND EXCEPTIONS 15

C++ Streams – Unformatted I/O - Formatted Console I/O – Opening and Closing File – File
modes - File pointers and their manipulations – Templates – Class Templates – Function Templates
- Exception handling.
Lab Exercises

1. Write C/C++ programs for the following:


a. Find the sum of individual digits of a positive integer.
b. Compute the GCD of two numbers.
c. Find the roots of a number (Newton‘s method)
2. Write C/C++ programs using arrays:
a. Find the maximum of an array of numbers.
b. Remove duplicates from an array of numbers.
c. Print the numbers in an array after removing even numbers.
4. Syllabus Contd...
3. Write C/C++ programs using strings:
a. Checking for palindrome.
b. Count the occurrences of each character in a given word.
4. Generate salary slip of employees using structures and pointers. Create a structure
Employee with the following members:
EID, Ename, Designation, DOB, DOJ, Basicpay
Note that DOB and DOJ should be implemented using structure within structure.
5. Compute internal marks of students for five different subjects using structures and
functions.
6. Write a program Illustrating Class Declarations, Definition, and Accessing Class
Members.
7. Program to illustrate default constructor, parameterized constructor and copy
constructors
8. Write a Program to Demonstrate the i) Operator Overloading. ii) Function Overloading.
9. Write a Program to Demonstrate Friend Function and Friend Class.
10. Program to demonstrate inline functions.
11. Program for Overriding of member functions.
12. Write C++ programs that illustrate how the following forms of inheritance are
supported:
a) Single inheritance b)Multiple inheritance c)Multi level inheritance d)Hierarchical
inheritance
13. Program to demonstrate pure virtual function implementation.
14. Count the number of account holders whose balance is less than the minimum balance
using sequential access file.
15. Write a Program to Demonstrate the Catching of all Exceptions.
16. Mini project.
TOTAL: 45+30 = 75 PERIODS
TEXT BOOKS:
1. Herbert Schildt, “The Complete Reference C++”, 4th edition, MH, 2015. (Unit 1 & 2)
2. E Balagurusamy,”Object Oriented Programming with C++”, 4th Edition, Tata McGraw-
Hill Education, 2008. (Unit 3, 4 & 5)

REFERENCES:
1. Nell Dale, Chip Weems, “Programming and Problem Solving with C++”, 5th Edition,
Jones and Barklett Publishers, 2010.
2. John Hubbard, “Schaum's Outline of Programming with C++”, MH, 2016.
3. Yashavant P. Kanetkar, “Let us C++”, BPB Publications, 2020
4. ISRD Group, “Introduction to Object-oriented Programming and C++”, Tata McGraw-
Hill Publishing Company Ltd., 2007.
5. D. S. Malik, “C++ Programming: From Problem Analysis to Program Design”, Third
Edition, Thomson Course Technology, 2007.
6. https://infyspringboard.onwingspan.com/web/en/aptoclex_auth_01297200240671948
837_shared/overview
5. Course Outcomes

CO1: Solve problems using basic constructs in C.

CO2: Implement C programs using pointers and functions.

CO3: Apply object-oriented concepts and solve real world problems.

CO4: Develop C++ programs using operator overloading and polymorphism.

CO5: Implement C++ programs using Files and Exceptions.


6. CO - PO Mapping
POs and PSOs

PO PO PO PO PO PO PO PO PO PO PO PO PS PS PS
COs 1 2 3 4 5 6 7 8 9 10 11 12 O1 O2 O3

CO1 3 3 3 3 3 2 1

CO2 3 3 3 3 3 3 3 1

CO3 3 3 3 3 3 3 3 3 3 3 3 3 1

CO4 3 3 3 3 3 3 3 1

CO5 3 3 3 3 3 3 3 1
7. Lecture Plan - Unit IV
No.
S. of Proposed Actual Pertaining Taxonomy Mode of
Topic
No. Period Date Lecture CO Level Delivery
s Date

Operator
1 Chalk &
Overloading 1 CO4 K2
Talk
Overloading Using
2 1 CO4 Chalk &
Friend functions K3
Talk

3
Inheritance 1 CO4
K2
Chalk &
Talk
Types of
4 1 CO4 Chalk &
inheritance K2
Talk

5 Virtual Base Class 1 CO4


K2
Chalk &
Talk

6 Abstract Class 1 CO4


K2
Chalk &
Talk
Constructors in
7 1 CO4 Chalk &
Derived Classes K3
Talk

8 member class 1 CO4


K2
Chalk &
Talk

9 Nesting of classes. 1 CO4


K2
Chalk &
Talk

10 Pointer to objects 1 CO4


K3
Chalk &
Talk

11 this pointer 1 CO4


K2
Chalk &
Talk
Pointer to derived
12 1 CO4 Chalk &
Class K2
Talk

13 Virtual functions 1 CO4


K2
Chalk &
Talk
Pure Virtual
14 1 CO4 Chalk &
Functions K2
Talk

15 Polymorphism 1 CO4
K2
Chalk &
Talk
8. Activity Based Learning
Learning Method Activity

Tutorial Sessions available


Learn by Solving Problems
in Skillrack for Practice

Quiz / MCQ Using RMK


Learn by Questioning
Nextgen App

Learn by doing Hands-on Practice in Lab


9. Lecture Notes
UNIT IV OPERATOR OVERLOADING, INHERITANCE AND
POLYMORPHISM 15
Operator Overloading - Overloading Using Friend functions - Inheritance -
Types of inheritance - Virtual Base Class - Abstract Class - Constructors in
Derived Classes - member class: nesting of classes - Pointer to objects - this
pointer- Pointer to derived Class - Virtual functions - Pure Virtual Functions -
Polymorphism
4.1 Overloading
Over Loading
Creating two or more members having the same name but different in number or
type of parameter/arguments is known as overloading. In C++, we can overload:
Function, Operator and Constructor
Types of overloading in C++ are:

❖ Function Over Loading


❖ Operator Over Loading
Function Overloading
Function Overloading is defined as the process of having two or more function with
the same name. In function overloading, the function is redefined by using either different
types of arguments or a different number of arguments. It is only through these
differences compiler can differentiate between the functions.
Example Program
#include<iostream>
using namespace std;
class Calculate
{
public:
int add(int a,int b)
{ return a + b; }
int add(int a, int b, int c)
{ return a + b + c; }
};
int main(void)
{
//class object declaration.
Calculate C;
cout << "Sum of Two Numbers is : " << C.add(10,20) << endl;
cout << "Sum of Three Numbers is : " << C.add(12,20,23);
return 0;
}

Output
Sum of Two Numbers is : 30
Sum of Three Numbers is : 55
4.1 Operator Overloading
Operator Over Loading
In C++, we can change the way operators work for user-defined types like objects
and structures. This is known as operator overloading. For example,
Suppose we have created three objects c1, c2 and result from a class named
Complex that represents complex numbers.
Since operator overloading allows us to change how operators work, we can
redefine how the + operator works and use it to add the complex numbers of c1 and c2
by writing the following code:
result = c1 + c2;
instead of using
result = c1.addNumbers(c2);
This makes our code intuitive and easy to understand.
Syntax for C++ Operator Overloading
To overload an operator, we use a special operator function. We define the
function inside the class or structure whose objects/variables we want the overloaded
operator to work with.
class className
{ ... .. ...
public returnType operator symbol (arguments)
{ ... .. ...
}
... .. ...
};
Here,
returnType is the return type of the function.
operator is a keyword.
symbol is the operator we want to overload. Like: +, <, -, ++, etc.
arguments is the arguments passed to the function.
4.1 Operator Overloading
Program Example
#include <iostream>
using namespace std;
class Complex
{
private:
float real;
float imag;
public:
Complex()
{
real =0;
imag = 0;
}
void input()
{
cout << "Enter Real part : ";
cin >> real;
cout << "\nEnter Imaginary part : ";
cin >> imag;
}
// Operator overloading
Complex operator + (Complex c2)
{
Complex temp;
temp.real = real + c2.real;
temp.imag = imag + c2.imag;
return temp;
}
void output()
{
if(imag < 0)
cout << "Output Complex number : "<< real << imag << "i";
else
cout << "Output Complex number : " << real << " + " << imag <<
"i";
}
};
4.1 Operator Overloading
Program Example Contd…
int main()
{
Complex c1, c2, result;
cout<<"Enter first complex number : \n";
c1.input();
cout << endl;
cout<<"Enter second complex number : \n";
c2.input();

/* In case of operator overloading of binary


operators in C++ programming, the object on right hand
side of operator is always assumed as argument by
compiler.*/

result = c1 + c2;
result.output();

return 0;
}

Output

Enter first complex number :


Enter Real part : 5

Enter Imaginary part : 5

Enter second complex number :


Enter Real part : 5

Enter Imaginary part : 5

Output Complex number : 10 + 10i


4.2 Overloading Using Friend functions
Introduction
Data hiding is a fundamental concept of object-oriented programming. It restricts the
access of private members from outside of the class.
Similarly, protected members can only be accessed by derived classes and are
inaccessible from outside. For example,
class MyClass
{
private:
int member1;
}
int main()
{
MyClass obj;
// Error! Cannot access private members from here.
obj.member1 = 5;
}
However, there is a feature in C++ called friend functions that break this rule and allow
us to access member functions from outside the class.
friend Function
A friend function can access the private and protected data of a class. We declare a
friend function using the friend keyword inside the body of the class.
Syntax
class className
{
... .. ...
friend returnType functionName(arguments);
... .. ...
}
Characteristics of a Friend function:
1. The function is not in the scope of the class to which it has been declared as a friend.
4.2 Overloading Using Friend functions
Characteristics of a Friend function: contd…
2. It cannot be called using the object as it is not in the scope of that class.
3. It can be invoked like a normal function without using the object.
4. It cannot access the member names directly and has to use an object name and dot
membership operator with the member name.
5. It can be declared either in the private or the public part.
Program Example
#include<iostream>
using namespace std;
class integer
{
int num1, num2;
public:
void setValue()
{
num1 = 50;
num2 = 30;
}
//Declaration of friend Function
friend int mean(integer s);
};
//friend function definition
int mean(integer s)
{
return int(s.num1+s.num2) / 2.0;
}
int main()
{
integer c;
c.setValue();
cout<< "Mean value:" <<mean(c);
return 0;
}
Output
Mean value:40
4.2 Overloading Using Friend functions
Important points about operator overloading using friend function
1. An overloaded operator friend could be declared in either private or public section of a
class.
2. When an operator overloaded function is a friend function, it takes two operands of
user-defined data type.
3. When redefining the meaning of an operator by operator overloading friend function,
we cannot change its basic meaning. For example, we cannot redefine minus operator
to divide two operands of user-defined data-type.
Program Example
#include <iostream>
using namespace std;

class Complex
{
private:
float real;
float imag;
public:
Complex()
{
real =0;
imag = 0;
}
void input()
{
cout << "Enter Real part : ";
cin >> real;
cout << "\nEnter Imaginary part : ";
cin >> imag;
}

// Operator overloading using Friend function


friend Complex operator + (Complex c1, Complex c2);
4.2 Overloading Using Friend functions
Program Example Contd…
void output()
{
if(imag < 0)
cout << "Output Complex number : "<< real << imag << "i";
else
cout << "Output Complex number : " << real << " + " << imag << "i";
}
};

Complex operator+(Complex c1, Complex c2)


{
Complex temp;
temp.real = c1.real + c2.real;
temp.imag = c1.imag + c2.imag;
return(temp);
}

int main()
{
Complex c1, c2, result;

cout<<"Enter first complex number : \n";


c1.input();
cout << endl;
cout<<"Enter second complex number : \n";
c2.input();

result = c1 + c2;
result.output();

return 0;
}
4.2 Overloading Using Friend functions
Output
Enter first complex number :
Enter Real part : 9
Enter Imaginary part : 9
Enter second complex number :
Enter Real part : 10
Enter Imaginary part : 10
Output Complex number : 19 + 19i
Points to Remember While Overloading Operator using Friend Function:

❖ The Friend function in C++ using operator overloading offers better


flexibility to the class.

❖ The Friend functions are not a member of the class and hence they do
not have ‘this’ pointer.

❖ When we overload a unary operator, we need to pass one argument.

❖ When we overload a binary operator, we need to pass two arguments.

❖ The friend function in C++ can access the private data members of a
class directly.

❖ An overloaded operator friend could be declared in either the private or


public section of a class.

❖ · When redefining the meaning of an operator by operator overloading


the friend function, we cannot change its basic meaning. For example,
we cannot redefine plus operator + to multiply two operands of a
user-defined data type
4.3 Inheritance
Introduction
One of the most important concepts in object-oriented programming is that of
inheritance. Inheritance allows us to define a class in terms of another class, which makes
it easier to create and maintain an application. This also provides an opportunity to reuse
the code functionality and fast implementation time
Definition
Inheritance is one of the key features of Object-oriented programming in C++. It allows
us to create a new class (Derived Class) from an existing class (Base Class). Derived Class
object acquires all the properties and behaviors of its Base Class object automatically.
The derived class is the specialized class for the base class. Inheritance is an is-a
relationship. We use inheritance only if an is-a relationship is present between the two
classes. Here are some examples:
1. A car is a vehicle
2. Orange is a fruit.
Advantage of Inheritance
Code reusability: We can reuse the members of Base Class. So, there is no need to
define the member again. So less code is required in the Derived Class.
A derived class inherits all base class functions with the following exceptions
❖ Constructors, destructors and copy constructors of the base class.
❖ Overloaded operators of the base class.
❖ The friend functions of the base class.
Type of Inheritance
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
4.4 Types of inheritance

Single Inheritance is defined as the inheritance in which a derived class is


inherited from the only one base class.
In the diagram under Single inheritance box labelled “Base Class” is the base
class or Parent Class, and box labelled “Derived Class” is the Child Class
derived class.
It is the simplest among all the types of inheritance since it does not
include any kind of inheritance combination or different levels of inheritance.
The child class can inherit all the members of the base class according to the
visibility mode (i.e., private, protected, and public) that is specified during
the inheritance.
Syntax
class BaseClass
{
// code of class BaseClass
}
class DerivedClass : AccessModifier BaseClass
{
// code of class DerivedClass
}
4.4 Types of inheritance

Multiple inheritance is the process of deriving a new class that inherits the
attributes from two or more base classes.
In the above diagram, there are two-parent classes: Base Class 1 and
Base Class 2, whereas there is only one Child Class labelled “Derived Class”.
The Child Class acquires all features from both Base class 1 and Base class 2.
Therefore, we termed the type of Inheritance as Multiple Inheritance.
Syntax
class BaseClass1
{
// code of class BaseClass1
}
class BaseClass2
{
// code of class BaseClass2
}
class DerivedClass:AccessModifier BaseClass1,AccessModifier
BaseClass2
{
// code of class DerivedClass
}
4.4 Types of inheritance

Multilevel inheritance is a process of deriving a class from another


derived class. In C++ programming, not only we can derive a class from the
base class but we can also derive a class from the derived class. This form of
inheritance is known as multilevel inheritance.
Syntax
class BaseClass1
{
// code of class BaseClass1
}
class DerivedClass1 : AccessModifier BaseClass1
{
// code of class DerivedClass1
}
class DerivedClass2 : AccessModifier DerivedClass1
{
// code of class DerivedClass2
}
4.4 Types of inheritance

Hierarchical inheritance is defined as the process of deriving more than


one derived class from a single base class. Hierarchical Inheritance in C++
refers to the type of inheritance that has a hierarchical structure of classes.
A single base class can have multiple derived classes, can further inherit
these derived classes, forming a hierarchy of classes.
Syntax
class BaseClass
{
// code of class BaseClass
}
class DerivedClass1 : AccessModifier BaseClass
{
// code of class DerivedClass1
}
class DerivedClass2 : AccessModifier BaseClass
{
// code of class DerivedClass2
}
class DerivedClass3 : AccessModifier BaseClass
{
// code of class DerivedClass3
}
4.4 Types of inheritance

Hybrid inheritance is a combination of more than one type of inheritance.


Combining various types of inheritance like multiple, simple, and hierarchical
inheritance is known as hybrid inheritance. For instance, the combination of
single and hierarchical inheritance. Therefore, hybrid inheritance is also
known as multipath inheritance.
4.4 Types of inheritance
Single Inheritance is defined as the inheritance in which a derived class is
inherited from the only one base class.
Example Program
#include<iostream>
using namespace std;

class Employee // Base Class


{
public:
float salary = 900;
};
class Professor: public Employee // Derived Class
{
public:
float bonus = 100;
void sum()
{
cout << "Your Total Salary is: " << (salary + bonus);
}
};
int main()
{

// Creating an object of the derived class.


Professor p;
// Gets the salary variable of Employee class.
cout << "Your Salary is:" << p.salary << endl;
// Gets the bonus variable of the Professor class.
cout << "Your Bonus is:" << p.bonus << endl;
p.sum();
return 0;
}

Output
Your Salary is:900
Your Bonus is:100
Your Total Salary is: 1000
4.4 Types of inheritance
Multiple inheritance is the process of deriving a new class that inherits the
attributes from two or more base classes.
Example Program
#include <iostream>
using namespace std;
class Payroll // Base Class 1
{
public:
float basicPay = 900;
};

class Incentive // Base Class 2


{
public:
float bonus = 100;
};

// Deriving from Base Class1 and Base Class 2


class Salary: public Payroll, public Incentive
{
public:
void grossSalary()
{
cout << "Your Total Salary is: " << (basicPay + bonus);
}
};
int main()
{
// Creating an object of the Salary(derived) class
and
calling the grossSalary() function.
Salary s;
s.grossSalary();
return 0;
}
Output
Your Total Salary is:1000
4.4 Types of inheritance
Multilevel inheritance is a process of deriving a class from another
derived class.
Example Program
#include <iostream>
using namespace std;
class BaseClass
{
public:
void print()
{
cout << "This is an example of Multilevel
Inheritance";
}
};

class DerivedClass1: public BaseClass


{

};

// Here class is derived from another derived class.


class DerivedClass2: public DerivedClass1
{

};

int main()
{
DerivedClass2 Obj;
Obj.print();
return 0;
}
Output
This is an example of Multilevel Inheritance
4.4 Types of inheritance
Hierarchical inheritance is defined as the process of deriving more than
one derived class from a single base class.
Example Program
#include <iostream>
using namespace std;
class Base //single base class
{
public:
int x, y;
void getdata()
{
cout << "\nEnter value of x and y:\n"; cin >> x >> y;
}
};
class Derived1 : public Base
{
public:
void product()
{
cout << "\nProduct= " << x * y;
}
};
class Derived2 : public Base
{
public:
void sum()
{
cout << "\nSum= " << x + y;
}
};
int main()
{
Derived1 obj1; //object of derived class B
Derived2 obj2; //object of derived class C
obj1.getdata();
obj1.product();
obj2.getdata();
obj2.sum();
return 0;
}
4.4 Types of inheritance
Output
Enter value of x and y:
10
10
Product= 100
Enter value of x and y:
20
20
Sum= 40
4.4 Types of inheritance
Hybrid inheritance is a combination of more than one type of inheritance.
Example Program
#include <iostream>
using namespace std;
class World
{
public:
World()
{
cout << "This is World!\n";
}
};
// Here is Single Inheritance.
class Continent: public World {
public:
Continent()
{
cout << "This is Continent\n";
}};
class Country {
public:
Country()
{
cout << "This is the Country\n";
}
};
// Here is multiple Inheritance.
class India: public Continent, public Country {
public:
India()
{
cout << "This is India!";
}
};
int main()
{
India myworld;
return 0;
}
4.4 Types of inheritance
Output
This is World!
This is Continent
This is the Country
This is India!

Modes of inheritance in C++


There are three modes of inheritance:
1. Public mode
2. Protected mode
3. Private mode

Base class Type of Inheritance


member access
specifier Public Protected Private
Public Public Protected Private
Protected Protected Protected Private
Private Not accessible Not accessible Not accessible
4.5 Virtual Base Class
Virtual classes are primarily used during multiple inheritance. To avoid,
multiple instances of the same class being taken to the same class which
later causes ambiguity, virtual classes are used.
An ambiguity can arise when several paths exist to a class from the same
base class. This means that a child class could have duplicate sets of
members inherited from a single base class. C++ solves this issue by
introducing a virtual base class. When a class is made virtual, necessary care
is taken so that the duplication is avoided regardless of the number of paths
that exist to the child class.

Create class A
Declare the variable “int number” inside class A.
Class C and Class B get the “int number” variable from class A.
Class D is getting the “int number” from both class B, and Class C. This is not
good practice.
4.5 Virtual Base Class
We must avoid this redundancy and never inherit the same member for
example int number from multiple parent classes.
The solution to solve the above-mentioned problem is to make the parent
base class a virtual class.
Here, Class D is getting the “int number” directly from the parent base
virtual class.
4.5 Virtual Base Class
4.6 Abstract Class
An abstract class is a class that is designed to be specifically used as a base class. An
abstract class contains at least one pure virtual function. We declare a pure virtual
function by using a pure specifier (= 0) in the declaration of a virtual member function in
the class declaration. In other words, a function that has no definition. These classes
cannot be instantiated.
The classes inheriting the abstract class must provide a definition for the pure virtual
function; otherwise, the subclass would become an abstract class itself.
C++ Pure Virtual Functions
Pure virtual Functions are virtual functions with no definition. They start with virtual
keyword and ends with = 0. Here is the syntax for a pure virtual function,
virtual void functionname() = 0;
Note: The = 0 syntax doesn't mean we are assigning 0 to the function. It's just the way
we define pure virtual functions.
Pure virtual functions are used
❖ if a function doesn't have any use in the base class
❖ but the function must be implemented by all its derived classes
Let's take an example,
Suppose, we have derived Triangle, Square and Circle classes from the Shape class,
and we want to calculate the area of all these shapes. In this case, we can create a pure
virtual function named calculateArea() in the Shape. Since it's a pure virtual function, all
derived classes Triangle, Square and Circle must include the calculateArea() function with
implementation. A pure virtual function doesn't have the function body and it must end
with = 0. For example,
class Shape
{
public:
// creating a pure virtual function
virtual void calculateArea() = 0;
};
Example Program 4.6 Abstract Class
#include <iostream>
using namespace std;
// Abstract class
class Shape
{
protected:
float dimension;

public:
void getDimension()
{
cin >> dimension;
}
// pure virtual Function
virtual float calculateArea() = 0;
};
// Derived class
class Square : public Shape
{
public:
float calculateArea()
{
return dimension * dimension;
}
};
// Derived class
class Circle : public Shape
{
public:
float calculateArea()
{
return 3.14 * dimension * dimension;
}
};
int main()
{
Square square;
Circle circle;
cout << "Enter the length of the square: ";
square.getDimension();
cout << "Area of square: " << square.calculateArea() << endl;
cout << "\nEnter radius of the circle: ";
circle.getDimension();
cout << "Area of circle: " << circle.calculateArea() << endl;
return 0;
}
4.6 Abstract Class
Output
Enter the length of the square: 10
Area of square: 100

Enter radius of the circle: 30


Area of circle: 2826

Characteristics of Abstract Class


1. A class is abstract if it has at least one pure virtual function.
2. Abstract Classes cannot be instantiated, i.e. We cannot create an object of an
abstract class. But pointers and references of Abstract Class types can be created.
3. Classes that inherit the Abstract Class must implement all pure virtual functions. If
they do not, those classes will also be treated as abstract classes.
4. If we do not override the pure virtual function in derived class, then derived class
also becomes abstract class.
5. An abstract class can have constructors.
6. An abstract class in C++ can also be defined using struct keyword.
4.7 Constructors in Derived Classes
Constructors
Constructor in C++ is a special method that is invoked automatically at the time
of object creation. It is used to initialize the data members of new objects.
The constructor in C++ has the same name as the class. Constructor is invoked
at the time of object creation. It constructs the values i.e. provides data for the object
at the time of object creation. There fore it is known as constructors. Constructor does
not have a return value, hence they do not have a return type.
Derived Class
A derived class is a class created or derived from another existing class. The
existing class from which the derived class is created through the process of
inheritance is known as a base class.
Derived classes are used for augmenting the functionality of base class by
adding or modifying the properties and methods to suit the requirements of the
specialization necessary for derived class.
Constructors in Derived Classes
Whenever object of a class is created, the default constructor of that class is
invoked automatically to initialize the members of the class.
If a class is inherited from another class and an object of the derived class is
created , it is clear that the default constructor of the derived class will be invoked but
before that, the default constructor of all of the base classes will be invoked
That is the order of invocation is that the base class’s default constructor will be
invoked first and then the derived class’s default constructor will be invoked.
Reason for calling base class’s constructor on creating an object of derived
class
When a class is inherited from other, the data members and member functions
of base class comes automatically in derived class based on the access specifier but the
definition of these members exists in base class only.
4.7 Constructors in Derived Classes
When we create an object of derived class, all of the members of derived class
must be initialized but the inherited members in derived class can only be initialized
by the base class’s constructor as the definition of these members exists in base class
only. This is why the constructor of base class is called first to initialize all the
inherited members.

Example Program :
#include <iostream>
using namespace std;
// Base Class
class Parent
{
public:
// Base Class Constructor
Parent()
{
cout << "Inside Base Class" << endl;
}
};
// Child Class
class Child : public Parent
{
public:
// Clild Class Constructor
Child()
{
cout << "Inside Child Class" << endl;
}
};
// main() function
int main()
{
// Creating object of Child Class
Child object;
return 0;
}
Output:
Inside Base Class
Inside Child Class
4.8 Member Class
Class
A class in C++ is a user-defined type or data structure declared with keyword
class that has data and functions (also called member variables and member
functions) as its members whose access is governed by the three access specifiers
private, protected or public. By default access to members of a C++ class is private
Nested Class
A declaration of a class may appear within another class. Such declaration
declares a nested class.
Explanation
A nested class is a class which is declared in another enclosing class. A nested
class is a member and as such has the same access rights as any other member.
Member functions of a nested class follow regular access rules and have no special
access privileges to members of their enclosing classes. Member functions of the
enclosing class have no special access to members of a nested class.
The scope of a nested class is valid only within the scope of the enclosing
class. This increases the use of encapsulation and creates more readable and
maintainable code
Note: Nested class in C++ can be accessed outside the enclosing class
using scope resolution operator(::) . If nested class is declared after public access
specifiers inside the enclosing class then you must add scope resolution (::) during
creating its object inside main function.
Syntax:
class EnclosingClass
{
class NestedClass
{
};
};
4.9 Nesting of Classes
Example Program
#include<iostream>
using namespace std;
class EnclosingClass
{
public:
//Declaring Nested Class
class NestedClass
{
private:
int number;

public:
void setData(int num1)
{
number = num1;
}

void showData()
{
cout << "The number is: " << number;
}
};
};

int main()
{
// :: used to create object of nested class
EnclosingClass :: NestedClass obj1;
obj1.setData(100);
obj1.showData();
return 0;
}

Output

The number is: 100


4.9 Nesting of Classes

Members of the Inner class (Nested)


The Inner class is having one non-static data member that is x of value 20. Then it is
having a function show. So, we have written Inner class inside Outer class. Only
classes are there but we have to create objects also.
Members of the Outer class (Enclosing)
Two members are there, non-static and static.
Now let us learn a few things.
The first point is, can the Inner class access a and b members of the outer class? In
the Inner class function show, can we write cout << a? No, it cannot access a.
Because a is a non-static member. Can we access b? Yes, we can access it. So the
first point we learned is that the Inner class can access the members of the Outer
class if they are static.
Second point, can the Outer class create the object of the Inner class? Yes, it can.
Now using that object can it access all the members of a class? Yes, the Outer class
can access all the members of the class. It is just like as if it is a class outside.
Instead of writing it outside, we are writing inside the class so that it is visible only
here.
4.10 Pointer to Objects
A pointer is a variable that stores the memory address of another
variable (or object) as its value. A pointer aims to point to a data type which
may be int, character, double, etc.
Pointers to objects aim to make a pointer that can access the object,
not the variables. Pointer to object in C++ refers to accessing an object.
There are two approaches by which you can access an object. One is
directly and the other is by using a pointer to an object in c++.
A pointer to an object in C++ is used to store the address of an object.
For creating a pointer to an object in C++, we use the following syntax
Classname * pointertoobject;
For storing the address of an object into a pointer in c++, we use the
following syntax
Pointertoobject = &objectname;
After storing the address in the pointer to the object, the member
function can be called using the pointer to the object with the help of an
arrow operator [ ->].

In the below example Labeled Program 1, a simple class named


MyClass is created. An object of the class is defined as named object. Here a
pointer is also defined named p. In the program given below program, it is
shown how can we access the object directly and how can we use the pointer
to access the object directly.
4.10 Pointer to Objects
Program 1
#include <iostream>
using namespace std;
class MyClass
{
int num;
public:
void setNumber(int value)
{
num = value;

}
void showNumber();
};
void MyClass::showNumber()
{
cout << "The Number is "<<num << "\n";
}

int main()
{
MyClass object, *p; // an object is declared and a pointer to
it

object.setNumber(100); // object is accessed directly


object.showNumber();

p = &object; // the address of the object is assigned to p


p->showNumber(); // object is accessed using the pointer
return 0;
}

Output
The Number is 100
The Number is 100
4.10 Pointer to Objects
Program 2
#include<iostream>
using namespace std;

class Complex
{
int real, imaginary;
public:
void get_Data()
{
cout << "The real part is “ << real << endl;
cout << "The imaginary part is “ << imaginary << endl;
}

void set_Data(int x, int y)


{
real = x;
imaginary = y;
}
};

int main(){
Complex *ptr = new Complex;
ptr->set_Data(1, 54);
ptr->get_Data();

// Array of Objects
Complex *ptr1 = new Complex[4];
ptr1->set_Data(1, 4);
ptr1->get_Data();
return 0;
}
Output
The real part is 1
The imaginary part is 54
The real part is 1
The imaginary part is 4
4.11 this Pointer
Every object in C++ has access to its own address through an
important pointer called this pointer. The this pointer is an implicit
parameter to all member functions. Therefore, inside a member function,
this may be used to refer to the invoking object.
this pointer in C++ stores the address of the class instance, which is
called from the member function that enables functions to access the correct
object data members.
Friend functions do not have a this pointer, because friends are not
members of a class. Only member functions have a this pointer.
The this pointer is a pointer accessible only within the nonstatic
member functions of a class, struct, or union type. It points to the object for
which the member function is called. Static member functions don't have a
this pointer.
Syntax
this
this->member_identifier

There can be 3 main usage of this keyword in C++.


❖ It can be used to pass current object as a parameter to another method.
❖ It can be used to refer current class instance variable.
❖ It can be used to declare indexers.
4.11 this Pointer
Program

#include<iostream>
using namespace std;
class Employee
{
public:
int id;
string name;
float salary;
Employee(int id,string name, float salary)
{
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};

int main(void)
{
Employee e1 = Employee(101,"Sonoo",890000);
Employee e2 = Employee(102,"Nakul",59000);
e1.display();
e2.display();
return 0;
}
Output

101 Sonoo 890000


102 Nakul 59000
4.12 Pointer to Derived Class
We know that pointers are used for an object of derived classes, we
can also use them for the base objects. The pointer to the base class object
is type-compatible (can be used in two ways) with a pointer to the object of
the derived class.
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.
Class B
{
};
Class D : Public B
{
};
B *cptr; // here is pointer to class B type variable
B b; // base object
D d; // derived object
cptr=&b; // cptr points to object b
we can make in the above example cptr to point to the object d as follows
cptr=&d; // cptr points to object d
This is perfectly valid with C++ language because d is an object derived from
the class B
However these is a problem in using cptr to access the public of the
derived class D. using cptr we can access only those members which are
inherited from B and not the member that originally belongs to D. in case a
member of D class has the same name as one of the members of class B,
then any reference to that member by cptr variable will always access the
base class member.
4.12 Pointer to Derived Class
Program
#include<iostream>
using namespace std;
class BC
{
public:
int b;
void show()
{
cout << "b = : " << b << "\n";
}
};
class DC: public BC
{
public:
int d;
void show()
{
cout << "b = : " << b << "\n";
cout << "d = : " << d << "\n";
}
};
4.12 Pointer to Derived Class
Program
int main()
{
BC *bptr; // base pointer
BC base;
bptr = &base; //base address
bptr->b = 100; // access BC via base pointer
cout << "bptr points to base object \n";
bptr->show();
//derived class
DC derived;
bptr = &derived; // address of derived object
bptr->b = 200; // access DC via base pointer
/* bptr->d = 300; */ // won't work
cout << "bptr now points to derived object \n";
bptr->show(); //bptr now points to derived object
/* accessing d using a pointer of type derived class DC*/

DC *dptr; // derived type pointer


dptr = &derived;
dptr->d = 300;
cout << "dptr is derived type pointer \n";
dptr->show();
cout << "using ((DC*)bptr)\n";
((DC*)bptr)->d = 400;
((DC*)bptr)->show();
}
4.12 Pointer to Derived Class
Output
bptr points to base object
b = : 100
bptr now points to derived object
b = : 200
dptr is derived type pointer
b = : 200
d = : 300
using ((DC*)bptr)
b = : 200
d = : 400
Note: we have used the statement
bptr->show();
so two times first when bptr points to the base object, and second
when bptr is made to point to the derived object. but both the times, it
executed BC::show() function and displayed the content of the base
object. How ever the statements
dptr->show();
((DC *)bptr)->show(); // cast bptr to DC type
Display the contents of the derived object. This shows that, although a
base pointer can be made to point to any number of derived objects, it
cannot directly access the members defined by a derived class.
4.13 Virtual Function
A virtual function is a member function which 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 function.
Purpose and Characteristics of Virtual Function
❖ Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for function call.
❖ They are mainly used to achieve Runtime polymorphism
❖ Functions are declared with a virtual keyword in base class.
❖ The resolving of function call is done at runtime.

Rules for Virtual Functions


❖ Virtual functions must be members of some class.
❖ Virtual functions cannot be static members.
❖ They are accessed through object pointers.
❖ They can be a friend of another class.
❖ A virtual function must be defined in the base class, even though it is not
used.
❖ The prototypes of a virtual function of the base class and all the derived
classes must be identical. If the two functions with the same name but
different prototypes, C++ will consider them as the overloaded functions.
❖ We cannot have a virtual constructor, but we can have a virtual
destructor
4.13 Virtual Function
Example Program
#include <iostream>
using namespace std;

class Base
{
public:
virtual void print()
{
cout << "Printed from Base Class print() Function" << endl;
}
};

class Derived : public Base


{
public:
void print()
{
cout << "Printed from derived Class print() Function" << endl;
}
};

int main() {
Derived derived1;

// pointer of Base type that points to derived1


Base* base1 = &derived1;

// calls member function of Derived class


// virtual function bined at run time
base1->print();

return 0;
}

Output
Printed from derived Class print() Function
4.13 Virtual Function
Here, we have declared the print() function of Base as virtual.
So, this function is overridden even when we use a pointer of Base type that
points to the Derived object derived1.
Working of Virtual Function in C++

Runtime polymorphism is achieved only through a pointer (or reference)


of base class type. Also, a base class pointer can point to the objects of base
class as well as to the objects of derived class. In above code, base class
pointer ‘base1’ contains the address of object ‘derived1’ of derived class.
4.14 Pure Virtual Function
Pure virtual Functions are virtual functions with no definition. They start with
virtual keyword and ends with = 0. Here is the syntax for a pure virtual
function,
Syntax 1
virtual void functionname() = 0;
Note: The = 0 syntax doesn't mean we are assigning 0 to the function. It's
just the way we define pure virtual functions.
Syntax 2
virtual void functionname() {}
Pure virtual functions are used
❖ if a function doesn't have any use in the base class
❖ but the function must be implemented by all its derived classes
Let's take an example,
Suppose, we have derived Triangle, Square and Circle classes from the
Shape class, and we want to calculate the area of all these shapes. In this
case, we can create a pure virtual function named calculateArea() in the
Shape. Since it's a pure virtual function, all derived classes Triangle, Square
and Circle must include the calculateArea() function with implementation. A
pure virtual function doesn't have the function body and it must end with =
0. For example,
class Shape
{
public:
// creating a pure virtual function
virtual void calculateArea() = 0;
};
4.14 Pure Virtual Function
Example Program
#include <iostream>
using namespace std;
// Abstract class
class Shape
{
protected:
float dimension;

public:
void getDimension()
{
cin >> dimension;
}
// pure virtual Function
virtual float calculateArea() = 0; // Pure Virtual Function
};
// Derived class
class Square : public Shape
{
public:
float calculateArea()
{
return dimension * dimension;
}
};
// Derived class
class Circle : public Shape
{
public:
float calculateArea()
{
return 3.14 * dimension * dimension;
}
};
int main()
{
Square square;
Circle circle;
cout << "Enter the length of the square: ";
square.getDimension();
cout << "Area of square: " << square.calculateArea() << endl;
cout << "\nEnter radius of the circle: ";
circle.getDimension();
cout << "Area of circle: " << circle.calculateArea() << endl;
return 0;
}
4.14 Pure Virtual Function
Output
Enter the length of the square: 10
Area of square: 100

Enter radius of the circle: 30


Area of circle: 2826

Characteristics of Pure Virtual Function


1. A pure virtual function is a "do nothing" function. Here "do nothing"
means that it just provides the template, and derived class implements
the function.
2. It can be considered as an empty function means that the pure
virtual function does not have any definition relative to the base class.
3. Programmers need to redefine the pure virtual function in the
derived class as it has no definition in the base class.
4. A class having pure virtual function cannot be used to create direct
objects of its own. It means that the class is containing any pure virtual
function then we cannot create the object of that class. This type of
class is known as an abstract class.
4.14 Pure Virtual Function
Difference Between Virtual Function and Pure Virtual Function

S.No Virtual Function Pure Virtual Function

A pure virtual function is a


A virtual function is a member
member function in a base class
function in a base class that
1 whose declaration is provided in a
can be redefined in a derived
base class and implemented in a
class.
derived class.

The classes which are The classes which are containing

2 containing virtual functions are pure virtual function are the


not abstract classes. abstract classes.

In case of a virtual function, In case of a pure virtual function,

3 definition of a function is definition of a function is not


provided in the base class. provided in the base class.

The base class that contains a


The base class that contains a
pure virtual function becomes an
4 virtual function can be
abstract class, and that cannot be
instantiated.
instantiated.

If the derived class will not If the derived class does not
redefine the virtual function of define the pure virtual function; it

5 the base class, then there will will not throw any error but the
be no effect on the derived class becomes an abstract
compilation. class.

All the derived classes may or


All the derived classes must define
6 may not redefine the virtual
the pure virtual function.
function.
4.15 Polymorphism
Polymorphism is an important concept of object-oriented programming. The term
"Polymorphism" is the combination of "poly" + "morphs" which means many forms. It is a
greek word. That is, the same entity (function or operator) behaves differently in different
scenarios.
The + operator in C++ is used to perform two specific functions. When it is used
with numbers (integers and floating-point numbers), it performs addition.
int a = 5;
int b = 6;
int sum = a + b; // sum = 11
And when we use the + operator with strings, it performs string concatenation. For
example,

string firstName = “R.M.K. ";


string lastName = “Engineering College";
string name = firstName + lastName; // R.M.K. Engineering

College

Types of Polymorphism in C++


1. Compile-time Polymorphism.
2. Runtime Polymorphism.
4.15 Polymorphism
We can implement polymorphism in C++ using the following ways:
1. Function overloading
2. Operator overloading
3. Virtual functions
4. Function overriding
Difference Between Compile Time and Run Time Polymorphism

S.No Compile Time Polymorphism Run Time Polymorphism

The function to be invoked is The function to be invoked is


1
known at the compile time. known at the run time.

It is also known as overriding,


It is also known as overloading,
2 Dynamic binding and late
static binding and early binding.
binding.

Overloading is a compile time


Overriding is a run time
polymorphism where more than
polymorphism where more than
one method is having the same
3 one method is having the same
name but with the different
name, number of parameters
number of parameters or the
and the type of the parameters.
type of the parameters.

It is achieved by function
It is achieved by virtual
4 overloading and operator
functions and pointers.
overloading.

It provides fast execution as it is It provides slow execution as it


5
known at the compile time. is known at the run time.

It is less flexible as mainly all the


It is more flexible as all the
6 things execute at the compile
things execute at the run time.
time.
4.15 Polymorphism
Function overloading - Compile Time Polymorphism
When there are multiple functions with the same name but different
parameters, then the functions are said to be overloaded, hence this is
known as Function Overloading. Functions can be overloaded by changing
the number of arguments or/and changing the type of arguments.
Program
#include <iostream>
using namespace std;
// Function with 2 int parameters
int sum(int num1, int num2)
{
return num1 + num2;
}
// Function with 2 double parameters
double sum(double num1, double num2)
{
return num1 + num2;
}
// Function with 3 int parameters
int sum(int num1, int num2, int num3)
{
return num1 + num2 + num3;
}
int main()
{
// Call function with 2 int parameters
cout << "Sum of Two Integers using sum() = " << sum(5, 6) << endl;

// Call function with 2 double parameters


cout << "Sum of Two Double using sum() = " << sum(5.5, 6.6) << endl;

// Call function with 3 int parameters


cout << "Sum of Three Integers using sum() = " << sum(5, 6, 7) <<
endl;

return 0;
}

Output
Sum of Two Integers using sum() = 11
Sum of Two Double using sum() = 12.1
Sum of Three Integers using sum() = 18
4.15 Polymorphism
Operator overloading - Compile Time Polymorphism
we can overload an operator as long as we are operating on
user-defined types like objects or structures. We cannot use operator
overloading for basic types such as int, double, etc. Operator overloading is
basically function overloading, where different operator functions have the
same symbol but different operands. And, depending on the operands,
different operator functions are executed.
Program
##include <iostream>
using namespace std;
class Count
{
private:
int number;
public:
// Constructor to initialize count to 5
Count()
{
number = 5;
}
// Overload ++ when used as prefix
void operator ++()
{
number = number + 1;
}
void display()
{
cout << "Incremented value of member \"number\"
of object Count using overloaded operator ++ is :
" << number << endl;
}
};
4.15 Polymorphism
int main()
{
Count count1;
// Call the "void operator ++()" function
++count1;

count1.display();
return 0;
}

Output

Incremented value of member "number" of object Count


using overloaded operator ++ is : 6

Virtual Functions - Runtime Polymorphism


A virtual function is a function in a base class that is declared using the
keyword virtual. Defining in a base class a virtual function, with another
version in a derived class, signals to the compiler that we don't want static
linkage for this function.
What we want is the selection of the function to be called at any given point
in the program to be based on the kind of object for which it is called. This
sort of operation is referred to as dynamic linkage, or late binding.

Pure Virtual Functions - Runtime Polymorphism


It is possible that you want to include a virtual function in a base class
so that it may be redefined in a derived class to suit the objects of that class,
but that there is no meaningful definition you could give for the function in
the base class.
We can change the virtual function area() in the base class to the following −
virtual function area() = 0
The = 0 tells the compiler that the function has no body and above virtual
function will be called pure virtual function.
4.15 Polymorphism
Program
#include <iostream>
using namespace std;

class Shape
{
protected:
int width, height;

public:
Shape( int a = 0, int b = 0)
{
width = a;
height = b;
}
virtual int area()
{
cout << "Parent class area :" << width * height << endl;
return width * height;
}
};
class Rectangle: public Shape
{
public:
Rectangle( int a = 0, int b = 0)
{
width = a;
height = b;
}

int area ()
{
cout << "Rectangle class area : " << width * height << endl;
return (width * height);
}
};
4.15 Polymorphism
Program Contd…
class Triangle: public Shape
{
public:
Triangle( int a = 0, int b = 0)
{
width = a;
height = b;
}
int area ()
{
cout << "Triangle class area : " << (width * height)/2 <<
endl;
return (width * height / 2);
}
};

// Main function for the program


int main() {
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);

// store the address of Rectangle


shape = &rec;

// call rectangle area.


shape->area();

// store the address of Triangle


shape = &tri;

// call triangle area.


shape->area();

return 0;
}

Output
Rectangle class area : 70
Triangle class area : 25
10. Assignment Questions
S.No K-
Write Programs for the following COs
. Level
Overload the binary operator - to find the
1 K3 CO4
difference between two complex numbers
Create a class named Vehicle with two data
member named mileage and price. Create its
two subclasses
❖ Car with data members to store ownership
cost, warranty (by years), seating capacity
and fuel type (diesel or petrol).
❖ Bike with data members to store the
number of cylinders, number of gears, cooling
type(air, liquid or oil), wheel type(alloys or
spokes) and fuel tank size(in inches)
2 ❖ Make another two subclasses Audi and Ford K3 CO4
of Car, each having a data member to store
the model type.
❖ Next, make two subclasses Bajaj and TVS,
each having a data member to store the
make-type.
Now, store and print the information of an
Audi and a Ford car (i.e. model type,
ownership cost, warranty, seating capacity,
fuel type, mileage and price.)
❖ Do the same for a Bajaj and a TVS bike.
Create a class named Shape with a function
that prints "This is a shape". Create another
class named Polygon inheriting the Shape
class with the same function that prints
"Polygon is a shape". Create two other classes
named Rectangle and Triangle having the
3 same function which prints "Rectangle is a K3 CO4
polygon" and "Triangle is a polygon"
respectively. Again, make another class
named Square having the same function
which prints "Square is a rectangle".
Now, try calling the function by the object of
each of these classes
11. Part A
Question & Answer
1.
Part A
Define Over Loading (CO4, K1)
An overloaded declaration is a declaration that is declared with the same name
as a previously declared declaration in the same scope, except that both declarations
have different arguments and obviously different definition (implementation).

2. List the types of Over Loading (CO4, K2)

Types of overloading in C++ are:

❖ Function overloading

❖ Operator overloading

3. What is Function Overloading? (CO4, K1)

Function Overloading is defined as the process of having two or more function


with the same name. In function overloading, the function is redefined by using either
different types of arguments or a different number of arguments.

4. Implement a C++ Code to Illustrate Function Overloading (CO4, K3)


#include<iostream>
using namespace std;
class Calculate
{
public:
int add(int a,int b)
{ return a + b; }
int add(int a, int b, int c)
{ return a + b + c; }
};
int main(void)
{
//class object declaration.
Calculate C;
cout << "Sum of Two Numbers is : " << C.add(10,20) << endl;
cout << "Sum of Three Numbers is : " << C.add(12,20,23);
return 0;
}
5. Define Operator Over Loading. Operator Over Loading. (CO4, K1)

we can change the way operators work for user-defined types like objects and
structures. This is known as operator overloading. we can redefine how the +
operator works and use it to add the complex numbers of c1 and c2
Part A
6. How to Overload an operator in C++ (CO4, K3)
To overload an operator, we use a special operator function. We define the
function inside the class or structure whose objects/variables we want the overloaded
operator to work with.
class className
{ ... .. ...
public returnType operator symbol (arguments)
{ ... .. ...
}
... .. ...
};
7. Define friend function (CO4, K1)

A friend function can access the private and protected data of a class. We declare
a friend function using the friend keyword inside the body of the class.

8. Illustrate the Syntax for friend Function. (CO4, K2)

Syntax
class className
{
... .. ...
friend returnType functionName(arguments);
... .. ...
}
9. List out the Characteristics of friend Function. (CO4, K1)

❖ The function is not in the scope of the class to which it has been declared as a friend.

❖ It cannot be called using the object as it is not in the scope of that class.

❖ It can be invoked like a normal function without using the object.

9. Give the advantages of friend Function. (CO4, K2)

The Friend function in C++ using operator overloading offers better flexibility
to the class.

The friend function in C++ can access the private data members of a class directly.
Part A
10. Define Inheritance (CO4, K1)
Inheritance is one of the key features of Object-oriented programming in C++. It
allows us to create a new class (Derived Class) from an existing class (Base Class).
Derived Class object acquires all the properties and behaviors of its Base Class object
automatically.

11. List the advantages of Inheritance. (CO4, K1)


Code reusability: We can reuse the members of Base Class. So, there is no need to
define the member again. So less code is required in the Derived Class.
Reduced time to develop an application

12. List the Types of Inheritance. (CO4, K1)

Single inheritance
Multiple inheritance
Multilevel inheritance
Hierarchical inheritance
Hybrid inheritance
13. Give the Syntax for Single Inheritance. (CO4, K2)
Syntax
class BaseClass
{
// code of class BaseClass
}
class DerivedClass : AccessModifier BaseClass
{
// code of class DerivedClass
}
14. Give the Syntax for Multiple Inheritance. (CO4, K2)
Syntax
class BaseClass1
{
// code of class BaseClass1
}
class BaseClass2
{
// code of class BaseClass2
}
class DerivedClass:AccessModifier BaseClass1,AccessModifier
BaseClass2
{
// code of class DerivedClass }
Part A
15. Give the Syntax for Multi Level Inheritance. (CO4, K2)
Syntax
class BaseClass1
{
// code of class BaseClass1
}
class DerivedClass1 : AccessModifier BaseClass1
{
// code of class DerivedClass1
}
class DerivedClass2 : AccessModifier DerivedClass1
{
// code of class DerivedClass2
}
16. Give the Syntax for Hierarchical Inheritance. (CO4, K2)
Syntax
class BaseClass
{
// code of class BaseClass
}
class DerivedClass1 : AccessModifier BaseClass
{
// code of class DerivedClass1
}
class DerivedClass2 : AccessModifier BaseClass
{
// code of class DerivedClass2
}
class DerivedClass3 : AccessModifier BaseClass
{
// code of class DerivedClass3
17. Demonstrate the need for Virtual Class (CO4, K1)
Virtual classes are primarily used during multiple inheritance. To avoid, multiple
instances of the same class being taken to the same class which later causes ambiguity,
virtual classes are used.

18. Write note on Abstract Class. (CO4, K2)


An abstract class is a class that is designed to be specifically used as a base class. An
abstract class contains at least one pure virtual function. We declare a pure virtual
function by using a pure specifier (= 0) in the declaration of a virtual member function
in the class declaration. In other words, a function that has no definition. These classes
cannot be instantiated.
Part A
19. Define Constructor. (CO4, K1)
Constructor in C++ is a special method that is invoked automatically at the time
of object creation. It is used to initialize the data members of new objects.

20. Give the example for Constructor. (CO4, K2)


Example
class Example
{
public:
Example()
{
}
Example(int a, int b)
{
// Parameterized constructor.

}
private:
int x_;
int y_;
};
21. Demonstrate the usage of Pointer to Object (CO4, K3)
A pointer to an object in C++ is used to store the address of an object. For creating a
pointer to an object in C++, we use the following
syntax
Classname * pointertoobject;
For storing the address of an object into a pointer in c++, we use the following
syntax
Pointertoobject = &objectname;
After storing the address in the pointer to the object, the member function can
be called using the pointer to the object with the help of an arrow operator [ ->].
Part A
22. Define tis pointer. (CO4, K1)
The this pointer is a pointer accessible only within the nonstatic member
functions of a class, struct, or union type. It points to the object for which the member
function is called. Static member functions don't have a this pointer.
Syntax
this
this->member_identifier

23. Give the usage of this pointer. (CO4, K2)


Two main usage of this keyword in C++.

❖ It can be used to pass current object as a parameter to another method.

❖ It can be used to refer current class instance variable.

24. Define Virtual Function (CO4, K1)

A virtual function is a member function which is declared within a base class and is
re-defined (overridden) by a derived class.

25. Purpose and Characteristics of Virtual Function. (CO4, K2)

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

of the type of reference (or pointer) used for function call.

❖ They are mainly used to achieve Runtime polymorphism

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

❖ The resolving of function call is done at runtime.

26. Give the syntax for defining Pure Virtual Function. (CO4, K2)

Syntax 1

virtual void functionname() = 0;

Note: The = 0 syntax doesn't mean we are assigning 0 to the function. It's just the
way we define pure virtual functions.

Syntax 2

virtual void functionname() {}


Part A
27. Distinguish Virtual Function and Pure Virtual Function. (CO4, K2)

S.No Virtual Function Pure Virtual Function

A pure virtual function is a


A virtual function is a member
member function in a base class
function in a base class that
1 whose declaration is provided in a
can be redefined in a derived
base class and implemented in a
class.
derived class.

The classes which are The classes which are containing

2 containing virtual functions are pure virtual function are the


not abstract classes. abstract classes.

28. Illustrate the Types of Polymorphism. (CO4, K2)


Part A
29. Distinguish Compile Time and Run Time Polymorphism. (CO4, K2)

S.No Compile Time Polymorphism Run Time Polymorphism

The function to be invoked is The function to be invoked is


1
known at the compile time. known at the run time.

Overloading is a compile time


Overriding is a run time
polymorphism where more than
polymorphism where more than
one method is having the same
2 one method is having the same
name but with the different
name, number of parameters
number of parameters or the
and the type of the parameters.
type of the parameters.

It is achieved by function
It is achieved by virtual
3 overloading and operator
functions and pointers.
overloading.

It provides fast execution as it is It provides slow execution as it


4
known at the compile time. is known at the run time.

It is less flexible as mainly all the


It is more flexible as all the
5 things execute at the compile
things execute at the run time.
time.

30. How can we Implement Polymorphism in C++. (CO4, K2)


We can implement polymorphism in C++ using the following ways:

❖ Function overloading

❖ Operator overloading

❖ Virtual functions

❖ Function overriding
12. Part B Questions
12.PART – B Questions
1. Explain Function Overloading with a C++ Program. (CO4, K3)
2. Write a C++ program to demonstrate function overloading. (CO4, K3)
3. Write a C++ program to demonstrate the overloading of a unary operator. (CO4, K3)
4. Write a C++ program to demonstrate the overloading of a binary operator. (CO4, K3)
5. Explain Operator Overloading with a C++ Program. (CO4, K3)
6. Write a program to add two complex numbers using object as arguments. (CO4, K3)
7. Write a program to add two distances. (CO4, K3)
8. Discuss the role of access specifiers in inheritance and show their visibility when they
are inherited as public, private and protected. (CO4. K2)
9. Write a C++ Program to Illustrate Friend Function. (CO4, K3)
10. Explain the significance of Inheritance in Object Oriented Programming. (CO4, K1)
11. C++ program to read and print employee information using multiple inheritance.
(CO4, K3)
12. C++ program to demonstrate example of hierarchical inheritance to get square and
cube of a number. (CO4, K3)
13. C++ program to read and print employee information with department and PF
information using hierarchical inheritance. (CO4, K3)
14. Write a C++ Program to Illustrate types of inheritance. (CO4, K3)
15. Illustrate the role of Virtual Base Class in C++ with a complete Program. (CO4, K3)
16. How overriding is different from the overloading.
17. Explain the concept of polymorphism by an example in C. (CO4. K2)
18. Compare and Contrast late binding and early binding. (CO4. K2)
19. Write a C++ Program to demonstrate Run time polymorphism. (CO4, K3)
20. Write a C++ Program to illustrate the use of pure virtual function in Polymorphism.
(CO4, K3)
21. Write a C++ Program to define an Abstract Class in Polymorphism. (CO4, K3)
22. Write a C++ Program to illustrates the use of Virtual base class. (CO4, K3)
23. Write a C++ Program to show an Example of Pointers to base class. (CO4, K3)
24. Write a C++ Program to illustrate Abstract Base Class. (CO4, K3)
25. Write a C++ Program to illustrate an example of Pure Virtual functions. (CO4, K3)
26. Write a C++ Program to maintain employee database using virtual class. (CO4, K3)
13. Supportive online courses

❖ https://nptel.ac.in/courses/106105151
❖ https://nptel.ac.in/courses/106101208
❖ https://www.codecademy.com/learn/learn-c-plus-plus
❖ https://www.udemy.com/topic/c-plus-plus/
❖ https://www.edx.org/learn/c-plus-plus
❖ https://in.coursera.org/specializations/hands-on-cpp
❖ https://www.simplilearn.com/free-course-to-learn-cpp-basics-skillup
❖ https://www.codespaces.com/best-c-plus-plus-courses-tutorials-certifications
.html

❖ https://hackr.io/blog/cpp-course
❖ https://www.udacity.com/course/c-for-programmers--ud210

External Links for Additional Resources

❖ https://swayam.gov.in
❖ https://www.coursera.org
❖ https://www.udemy.com
❖ https://unacademy.com
❖ https://www.sololearn.com
❖ https://www.tutorialspoint.com
❖ https://www.w3schools.in
❖ https://www.geeksforgeeks.org
❖ https://www.programiz.com
14. Real Time Applications
Suppose a Car has two functions: accelerate and brake. Now these
functions have different values for different cars as every car has a
different acceleration rate and braking mechanisms. So let us take the
example of a Mercedes Benz S-Class which is a car. It inherits all the
definitions of the class Car. However its acceleration and braking
systems are unique.

If we develop any application using concept of Inheritance than that


application have following advantages,

Application development time is less.


Application take less memory.
Application execution time is less.
Application performance is enhance (Improved).
Redundancy (Repetition) of the code is reduced or minimized so that
we get consistence results and less storage cost.

In the above diagram data members and methods are represented in


broken line are inherited from faculty class and they are visible in student
class logically
15. Content Beyond Syllabus
Develop an banking application to demonstrate Banking
Operations Using Inheritance.
#include <iostream>
#include <stdlib.h>
using namespace std;

class person
{
protected:
char name[20];
int code;
public:
void getdetail(void)
{
cout<<"\n\nEnter name :- ";
cin>>name;
cout<<"\nEnter code :- ";
cin>>code;
}
void dispdetail(void)
{
cout<<"\n\nNAME :- "<<name;
cout<<"\nCODE :- "<<code;
}
};
15. Content Beyond Syllabus
class account : virtual public person
{
protected:
float pay;
public:
void getpay(void)
{
cout<<"\nEnter Pay amount :- ";
cin>>pay;
}
void dispay(void)
{
cout<<"\nPAY :- "<<pay;
}
};

class admin : virtual public person


{
protected:
int experience;
public:
void getexpr(void)
{
cout<<"\nEnter Experience in yrs :- ";
cin>>experience;
}
void dispexpr(void)
{
cout<<"\nEXPERIENCE:- "<<experience;
}
};
15. Content Beyond Syllabus
class master : public account, public admin
{
public:
void create(void)
{
cout<<"\n\n=====GETDATA IN=====\n";
getdetail();
getpay();
getexpr();
}

void display(void)
{
cout<<"\n\n=====DISPLAY DETAILS=====\n";
dispdetail();
dispay();
dispexpr();
}

void update(void)
{
cout<<"\n\n=====UPDATE DETAILS=====\n";
cout<<"\nChoose detail you want to update\n";
cout<<"1) NAME\n";
cout<<"2) CODE\n";
cout<<"3) EXPERIENCE\n";
cout<<"4) PAY\n";
cout<<"Enter your choice:- ";
int choice;
cin>>choice;
15. Content Beyond Syllabus

switch(choice)
{
case 1 : cout<<"\n\nEnter name : - ";
cin>>name;
break;
case 2 : cout<<"\n\nEnter code :- ";
cin>>code;
break;
case 3 : cout<<"\n\nEnter pay :- ";
cin>>pay;
break;
case 4 : cout<<"\n\nEnter Expereince :- ";
cin>>experience;
break;
default: cout<<"\n\nInvalid choice\n\n";
}
}
};
int main()
{
master ob1;
int choice;
while(1)
{
cout<<"\n\n=====EMPLOYE DATABASE=====\n\n";
cout<<"\nChoose Operation you want to
perform\n";
cout<<"1) Create Record\n";
cout<<"2) Display Record\n";
cout<<"3) Update Record\n";
cout<<"4) Exit\n";
cout<<"\nEnter your choice:- ";
cin>>choice;
15. Content Beyond Syllabus

switch(choice)

case 1 : ob1.create();

break;

case 2 : ob1.display();

break;

case 3 : ob1.update();

break;

case 4 : exit(1);

default : cout<<"\n\nInvalid Choice\nTry

Again\n\n";

return 0;
}
15. Content Beyond Syllabus

=====EMPLOYE DATABASE=====

Choose Operation you want to perform


1) Create Record
2) Display Record
3) Update Record
4) Exit

Enter your choice:- 1

=====GETDATA IN=====

Enter name :- Vijayakumar

Enter code :- 229

Enter Pay amount :- 75000

Enter Experience in yrs :- 23

=====EMPLOYE DATABASE=====

Choose Operation you want to perform


1) Create Record
2) Display Record
3) Update Record
4) Exit

Enter your choice:- 2


15. Content Beyond Syllabus
=====DISPLAY DETAILS=====

NAME :- Vijayakumar
CODE :- 229
PAY :- 75000
EXPERIENCE:- 23

=====EMPLOYE DATABASE=====

Choose Operation you want to perform


1) Create Record
2) Display Record
3) Update Record
4) Exit

Enter your choice:- 4

Exited…..
16. Assessment Schedule

Tentative schedule for the Assessment During 2022-2023 Odd semester

S. Name of the
Start Date End Date Portion
No. Assessment

1 Unit Test 1 24.11.2022 29.11.2022 Unit 1

2 IAT 1 07.12.2022 14.12.2022 Unit 1 & 2

3 Unit Test 2 Unit 3

4 IAT 2 23.01.2023 30.01.2023 Unit 3 & 4

5 Revision 1 11.02.2023 Unit 5, 1 & 2

6 Revision 2 13.02.2023 Unit 3 & 4

7 Model 15.02.2023 24.02.2023 All 5 Units


17. Text Books & References

Text Books:

1. Herbert Schildt, “The Complete Reference C++”, 4th edition, MH,


2015. (Unit 1 & 2)
2. E Balagurusamy,”Object Oriented Programming with C++”, 4th
Edition, Tata McGraw-Hill Education, 2008. (Unit 3, 4 & 5)

Reference Books:

1. Nell Dale, Chip Weems, “Programming and Problem Solving with


C++”, 5th Edition, Jones and Barklett Publishers, 2010.
2. John Hubbard, “Schaum's Outline of Programming with C++”, MH,
2016.
3. Yashavant P. Kanetkar, “Let us C++”, BPB Publications, 2020
4. ISRD Group, “Introduction to Object-oriented Programming and
C++”, Tata McGraw-Hill Publishing Company Ltd., 2007.
5. D. S. Malik, “C++ Programming: From Problem Analysis to Program
Design”, Third Edition, Thomson Course Technology, 2007.
6. https://infyspringboard.onwingspan.com/web/en/app/toc/lex_auth_01
297200240671948837_shared/overview
18. Mini Project Suggestions
1. Employee Management System Using Polymorphism. (CO1-CO4, K6)
2. Student Management System Using Inheritance. (CO1-CO4, K6)
3. Calculator Using Overloading Concept. (CO1-CO4, K6)
Thank you

Disclaimer:

This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not
the intended recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contents of this information is strictly prohibited.

You might also like