0% found this document useful (0 votes)
17 views

OBJECT ORIENTED PROGRAMMING USING C+++

The document provides an overview of Object-Oriented Programming (OOP) concepts in C++, including functions, classes, static members, this pointer, function overriding, derived classes, iterators, and the Standard Template Library (STL). It also discusses recursion, control structures (sequence, selection, iteration), and various types of operators (arithmetic, relational, logical, bitwise, and assignment) with examples. The content serves as a comprehensive guide for understanding fundamental OOP principles and programming constructs in C++.
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)
17 views

OBJECT ORIENTED PROGRAMMING USING C+++

The document provides an overview of Object-Oriented Programming (OOP) concepts in C++, including functions, classes, static members, this pointer, function overriding, derived classes, iterators, and the Standard Template Library (STL). It also discusses recursion, control structures (sequence, selection, iteration), and various types of operators (arithmetic, relational, logical, bitwise, and assignment) with examples. The content serves as a comprehensive guide for understanding fundamental OOP principles and programming constructs in C++.
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/ 33

OBJECT ORIENTED PROGRAMMING USING C++

MAY – 2024

1. (a) What is function ? Give example.


Ans. A function in C++ is a block of code that performs a specific
task, allowing you to reuse a set of instructions multiple times within
your program by calling the function name; essentially, it
encapsulates a calculation or operation that can be used with
different input values to produce a result.
For example, function strcat() to concatenate two strings, function
memcpy() to copy one memory location to another location and
many more functions.
(b) What is class ? Give example.
Ans. A "class" in C++ is a user-defined data type that acts as a
blueprint for creating objects, containing variables (data members)
and functions (member functions) that define the properties and
behaviors of those objects; essentially, it's a way to group related
data and operations together, allowing you to create multiple
instances with the same structure.
Example of a class
Student class
A class that might have data members like name, roll number, age,
and marks. The member functions could include updateMarks() and
getAge().
Car class
A class that might have data members like speed limit, mileage, and
number of wheels. The member functions could include apply brakes
and increase speed.
Room class
A class that might have data members like length, breadth, and
height. The member functions could include calculate_area() and
calculate_volume().
(c) What is static member ? Give example.
Ans. Static Member in C++
Just like a static variable once declared is allocated with memory that
can't be changed every object points to the same memory. To know
more about the topic refer to a static Member in C++.
Example: class Person{ static int index_number; };
(d) What is this pointer ? What is its importance ?
Ans. In C++, "this pointer" is a special, implicit pointer that
automatically exists within every non-static member function of a
class, pointing to the current object instance on which the member
function is being called; essentially, it allows the member function to
access the data members of the object it is operating on directly,
making it crucial for object-oriented programming within a class.
Importance : Pointers provide many capabilities to the C++ language.
It offers features like referring to the same space in memory from
over one memory location, i.e. you can change one location in the
program, and it can reflect those changes in other parts of the
program
(e) What is overriding ? Give example.
Ans. Function Overriding is the redefinition of the base class
function in its derived class with the same return type and
parameters. Class Base_calss { public: virtual void print() {
cout<<"Coding"<<endl; } }; Class Derived_class:public Base_class {
public: void print() { cout<<"Coding Ninjas"<<endl; } };
(f) What is the use of derived class ?
Ans. A derived class, also called a subclass or child class, is used in
object-oriented programming to create a new class that inherits the
properties and behaviors of an existing class (called the base class),
allowing you to extend functionality by adding new features while
reusing code from the base class without having to reimplement it
from scratch; essentially, it lets you specialize a base class to fit
specific needs by adding new attributes and methods.
(g) What is the use of iterator ?
Ans. An iterator is a programming concept used to traverse through
the elements of a collection (like a list, set, or map) one by one,
allowing you to access and potentially modify each element in a
sequential manner without needing to know the underlying data
structure details; essentially, it provides a standardized way to loop
through a collection's elements
(h) What is the importance of standered template library ?
Ans. The Standard Template Library (STL) is a crucial part of the C++
programming language, providing a collection of pre-built, generic
data structures (containers) and algorithms that can be used with
various data types, allowing developers to write efficient and
reusable code quickly, without needing to implement common
functionalities from scratch; essentially, it significantly speeds up
development by offering readily available tools for common
programming tasks like sorting, searching, and manipulating data.
UNIT – I
2. (a) What is importance of recursion ? Explain with the
help of C++ program.
Ans. Recursion is a programming technique where a function calls
itself, allowing you to break down complex problems into smaller,
more manageable subproblems, often resulting in concise and
elegant code, particularly when dealing with hierarchical structures
like trees or when a problem can be defined in terms of itself; in C++,
recursion is useful for situations like calculating factorials, traversing
tree structures, and solving problems like the Tower of Hanoi, where
the solution depends on solving smaller versions of the same
problem.
Explanation:
Base Case:
The if (n == 0) condition acts as the base case, which is the stopping
point for recursion. When n reaches 0, the function returns 1,
preventing an infinite loop.
Recursive Case:
The return n * factorial(n - 1) line is the recursive call. It calculates the
factorial of n by multiplying n with the factorial of (n - 1), effectively
breaking down the problem into smaller parts until the base case is
reached.
Key points about recursion:
Readability:
When used appropriately, recursion can make code more readable
and intuitive for problems with inherent recursive structures.
Efficiency:
While not always the most efficient approach, recursion can be very
effective for certain problems, especially when dealing with tree-like
data structures.
Stack Usage:
Each recursive call adds a new stack frame, so large recursive depths
can lead to stack overflow issues.
Important considerations when using recursion:
Base Case:
Always define a clear base case to ensure the recursion eventually
terminates.
Complexity Analysis:
Be aware of the potential time and space complexity of recursive
algorithms, as they can sometimes be less efficient than iterative
solutions.
(b) Discuss in detail all the control structures used in C++ by
giving examples.
Ans. In C++, the three primary control structures are: sequence,
selection (decision making), and iteration (looping), each allowing for
different flow of execution based on conditions within the program;
here's a breakdown with examples for each type:.
1. Sequence Control Structure:
Explanation: Statements are executed in the order they appear in the
code, line by line, without any conditional checks.
Example:
Code

int num1 = 10;

int num2 = 5;

int sum = num1 + num2;

cout << "The sum is: " << sum;


2. Selection Control Structure (Decision Making):
Explanation: Used to choose which block of code to execute based
on a condition being true or false.
Types:
if statement: Executes a block of code only if the condition is true.
if-else statement: Executes one block of code if the condition is true,
and another block if it's false.
switch-case statement: Checks a variable against multiple possible
values and executes the corresponding block of code.
Examples:
if statement:
Code

int age = 18;

if (age >= 18) {

cout << "You are eligible to vote." << endl;

}
if-else statement.
Code

int num = 10;

if (num % 2 == 0) {

cout << "Number is even." << endl;

} else {

cout << "Number is odd." << endl;

}
switch-case statement.
Code

char grade = 'B';

switch (grade) {
case 'A':

cout << "Excellent" << endl;

break;

case 'B':

cout << "Good" << endl;

break;

default:

cout << "Invalid grade" << endl;

}
3. Iteration Control Structure (Looping):
Explanation: Used to repeat a block of code multiple times until a
certain condition is met.
Types:
while loop: Continuously executes a block of code as long as a
condition remains true.
do-while loop: Executes a block of code at least once, then continues
to loop as long as a condition remains true.
for loop: Used for iterating a specific number of times, often with a
counter variable.
Examples:
while loop:
Code

int count = 1;
while (count <= 5) {

cout << count << endl;

count++;

}
do-while loop.
Code

int num = 0;

do {

cout << num << endl;

num++;

} while (num < 5);


for loop.
Code

for (int i = 0; i < 5; i++) {

cout << "Iteration: " << i << endl;

}
Key Points:
# Control structures are essential for creating complex logic in C++
programs by allowing for conditional execution and repetition.
# The choice of control structure depends on the specific problem
you are trying to solve and the desired flow of execution.
# Nested control structures (e.g., an if statement within another
loop) can be used to create more intricate decision-making logic.
3. (a) Explain all the operations used in C++ with help of
suitable C++ program examples.
Ans. C++ has many types of operators, including arithmetic,
relational, logical, and assignment operators.
Arithmetic operators in C++ are the basic operators, which
are used for basic mathematical or arithmetical operations on
operands. These operators are essential for performing
calculations and manipulating data within a program
# Addition (+): Adds two values together
# Subtraction (-): Subtracts the right operand from the left operand
# Multiplication ()*: Multiplies two values together
# Division (/): Divides the left operand by the right operand
# Modulus (%): Finds the remainder of a division
# Increment (++): Adds one to the value of a variable
# Decrement (--): Subtracts one from the value of a variable

Relational Operators
Relational operators are used to compare two values or
expressions. These operators return a boolean value − true if
the comparison is correct, and else false.

They are essential for making decisions and controlling the flow
of a program based on conditions.

There are following relational operators supported by C++


language

Assume variable A holds 10 and variable B holds 20, then −

Operator Description Example


Checks if the values of
== (A == B) is not true.
two operands are equal or
not, if yes then condition
becomes true.
Checks if the values of
two operands are equal or
!= not, if values are not equal (A != B) is true.
then condition becomes
true.
Checks if the value of left
operand is greater than the
> value of right operand, if (A > B) is not true.
yes then condition
becomes true.
Checks if the value of left
operand is less than the
< value of right operand, if (A < B) is true.
yes then condition
becomes true.
Checks if the value of left
operand is greater than or
>= equal to the value of right (A >= B) is not true.
operand, if yes then
condition becomes true.
Checks if the value of left
operand is less than or
<= equal to the value of right (A <= B) is true.
operand, if yes then
condition becomes true.

Logical Operators
Logical operators are used to perform logical operations on
boolean values (true or false). These operators are essential for
controlling the flow of a program based on conditions. There
are three primary logical operators in C++ as mentioned below

There are following logical operators supported by C++


language.
Assume variable A holds 1 and variable B holds 0, then −

Operator Description Example


Called Logical AND
operator. If both the
&& operands are non-zero, (A && B) is false.
then condition becomes
true.
Called Logical OR
Operator. If any of the two
|| (A || B) is true.
operands is non-zero, then
condition becomes true.
Called Logical NOT
Operator. Use to reverses
the logical state of its
! !(A && B) is true.
operand. If a condition is
true, then Logical NOT
operator will make false.

Bitwise Operators
Bitwise operators are used to perform operations at the bit
level on integer data types. These operations work on direct
manipulation of bits, such as low-level programming, graphics,
and cryptography.

Bitwise operator works on bits and perform bit-by-bit


operation. The truth tables for &, |, and ^ are as follows −

p q p&q p|q p^q


0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

Assume if A = 60; and B = 13; now in binary format they will


be as follows −
A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

The Bitwise operators supported by C++ language are listed in


the following table. Assume variable A holds 60 and variable B
holds 13, then −

Operator Description Example


Binary AND Operator
(A & B) will give 12
& copies a bit to the result if
which is 0000 1100
it exists in both operands.
Binary OR Operator
(A | B) will give 61 which
| copies a bit if it exists in
is 0011 1101
either operand.
Binary XOR Operator
(A ^ B) will give 49 which
^ copies the bit if it is set in
is 0011 0001
one operand but not both.
(~A ) will give -61 which
Binary Ones Complement
is 1100 0011 in 2's
~ Operator is unary and has
complement form due to a
the effect of 'flipping' bits.
signed binary number.
Binary Left Shift
Operator. The left
operands value is moved A << 2 will give 240
<<
left by the number of bits which is 1111 0000
specified by the right
operand.
>> Binary Right Shift A >> 2 will give 15 which
Operator. The left is 0000 1111
operands value is moved
right by the number of bits
specified by the right
operand.

Assignment Operators
Assignment operators are used to assign values to variables.
These operators allow you to set or update the value stored in
a variable.

There are following assignment operators supported by C++


language −

Operator Description Example


Simple assignment operator,
Assigns values from right C = A + B will assign
=
side operands to left side value of A + B into C
operand.
Add AND assignment
operator, It adds right
C += A is equivalent to
+= operand to the left operand
C=C+A
and assign the result to left
operand.
Subtract AND assignment
operator, It subtracts right
C -= A is equivalent to
-= operand from the left
C=C-A
operand and assign the result
to left operand.
Multiply AND assignment
operator, It multiplies right
C *= A is equivalent to
*= operand with the left
C=C*A
operand and assign the result
to left operand.
Divide AND assignment
C /= A is equivalent to C
/= operator, It divides left
=C/A
operand with the right
operand and assign the result
to left operand.
Modulus AND assignment
operator, It takes modulus
C %= A is equivalent to
%= using two operands and
C=C%A
assign the result to left
operand.
Left shift AND assignment C <<= 2 is same as C =
<<=
operator. C << 2
Right shift AND assignment C >>= 2 is same as C =
>>=
operator. C >> 2
Bitwise AND assignment C &= 2 is same as C = C
&=
operator. &2
Bitwise exclusive OR and C ^= 2 is same as C = C
^=
assignment operator. ^2
Bitwise inclusive OR and C |= 2 is same as C = C |
|=
assignment operator. 2

Misc Operators
Miscellaneous operators, often abbreviated as "misc operators",
include a variety of operators that don’t fit neatly into other
categories like arithmetic or logical operators. Here are some
common miscellaneous operators and their definitions −

The following table lists some other operators that C++


supports.

Sr.No Operator & Description


sizeof
1 sizeof operator returns the size of a variable. For example,
sizeof(a), where ‘a’ is integer, and will return 4.
Condition ? X : Y
2 Conditional operator (?). If Condition is true then it
returns value of X otherwise returns value of Y.
,
3 Comma operator causes a sequence of operations to be
performed. The value of the entire comma expression is the
value of the last expression of the comma-separated list.
. (dot) and -> (arrow)
4 Member operators are used to reference individual
members of classes, structures, and unions.
Cast
5 Casting operators convert one data type to another. For
example, int(2.2000) would return 2.
&
6 Pointer operator & returns the address of a variable. For
example &a; will give actual address of the variable.
*
7 Pointer operator * is pointer to a variable. For example
*var; will pointer to a variable var.

(b) What is Array ? How two dimensional array is declared


and defined in C++ ? Explain with the help of C++ program.
Ans. An array can be defined as a group or collection of similar kinds
of elements or data items that are stored together in contiguous
memory spaces. All the memory locations are adjacent to each other,
and the number of elements in an array is the size of the array.
In C++, a two-dimensional array is declared using the syntax
data_type array_name[rows][columns], where data_type specifies
the data type of each element, array_name is the name of the array,
rows defines the number of rows, and columns defines the number
of columns in the array; essentially creating a grid-like structure
where each element can be accessed using its row and column index.
Example C++ program demonstrating a 2D array declaration and
usage:
Code
#include <iostream>

using namespace std;

int main() {

// Declaring a 2D array of integers with 3 rows and 4 columns

int numbers[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};

// Accessing elements in the array

cout << "Element at row 1, column 2: " << numbers[1][1] << endl;
// Outputs: 6

// Looping through all elements of the array

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 4; j++) {

cout << numbers[i][j] << " ";

}
cout << endl;

return 0;

}
Explanation:
int numbers[3][4]:
This line declares a 2D array named numbers which can hold
integers. It has 3 rows and 4 columns.
{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}:
This part initializes the array with specific values, where each set of
curly braces represents a row.
Key points about 2D arrays:
Accessing elements:
To access an element in a 2D array, use
array_name[row_index][column_index].
Looping through elements:
To iterate through all elements of a 2D array, you typically need
nested loops, one loop for rows and another for columns.
Memory allocation:
In C++, 2D arrays are stored in row-major order, meaning the
elements of the first row are stored consecutively in memory,
followed by the elements of the second row, and so on.

UNIT – II
4. (a) What is the use of constructor ? Explain different
types of constructors by giving suitable C++ programs.
Ans. A constructor in C++ is a special member function that is
automatically called when an object of a class is created, and its
primary purpose is to initialize the object's data members, essentially
setting up the initial state of the newly created object; it has the
same name as the class and does not have a return type.
Different types of constructors:
Default Constructor:
A constructor that takes no parameters, used to initialize an object
with default values assigned by the compiler if no other constructor
is explicitly defined.
Parameterized Constructor:
A constructor that takes parameters, allowing you to specify initial
values for an object's data members when creating the object.
Copy Constructor:
A constructor that takes a reference to an existing object of the same
class, used to create a new object with the same values as the
existing one.
Example C++ Programs:
1. Default Constructor:
Code

class Person {

public:

string name;

int age;

Person() { // Default constructor


name = "Unknown";

age = 0;

};

int main() {

Person p1; // Uses the default constructor to initialize

cout << p1.name << " is " << p1.age << " years old." << endl;

return 0;

}
Explanation: When you create a Person object without passing any
arguments, the default constructor is called, setting the name to
"Unknown" and age to 0.
2. Parameterized Constructor:
Code

class Rectangle {

public:

double length, width;


Rectangle(double l, double w) { // Parameterized constructor

length = l;

width = w;

};

int main() {

Rectangle rect(5.0, 3.0); // Creates a rectangle with length 5 and


width 3

cout << "Area: " << rect.length * rect.width << endl;

return 0;

}
Explanation: This example allows you to specify the length and width
when creating a Rectangle object, using the values provided as
arguments to the parameterized constructor.
3. Copy Constructor:
Code

class Employee {

public:

string name;
int salary;

Employee(const Employee& other) { // Copy constructor

name = other.name;

salary = other.salary;

};

int main() {

Employee emp1("John", 50000);

Employee emp2 = emp1; // Uses the copy constructor

cout << emp2.name << " - " << emp2.salary << endl;

return 0;

}
Explanation: When you assign one Employee object to another
(emp2 = emp1), the copy constructor is called to create a new
Employee object with the same values as emp1.
Key points about constructors:
You can have multiple constructors with different parameter lists
(constructor overloading).
If you don't explicitly define any constructors for a class, the compiler
will automatically generate a default constructor.
Constructors are essential for proper object initialization in object-
oriented programming.
5. (a) Explain the concept of dynamic memory management
in C++ . Give C++ program to support your answer.
Ans. Dynamic memory management in C++ refers to the ability to
allocate memory at runtime, meaning during program execution, as
opposed to at compile time, allowing you to manage memory blocks
of varying sizes as needed by using the new operator to allocate
memory and the delete operator to deallocate it; this is crucial when
the exact memory requirements are not known beforehand, like
when working with data structures like linked lists or arrays whose
size can change dynamically.
Key points about dynamic memory management:
# Operators used: The new operator is used to allocate memory on
the heap, and the delete operator is used to free that allocated
memory.
# Pointer variables: Dynamically allocated memory is always
accessed using pointer variables.
# Memory leaks: Failing to deallocate memory using delete when it's
no longer needed can lead to memory leaks, which can significantly
impact program performance.
Example C++ program demonstrating dynamic memory allocation:
Code

#include <iostream>

using namespace std;


int main() {

int *ptr; // Declare a pointer variable

// Allocate memory for an integer using 'new'

ptr = new int;

// Assign a value to the allocated memory

*ptr = 10;

cout << "Value: " << *ptr << endl;

// Deallocate memory using 'delete'

delete ptr;

return 0;
}
Explanation:
1. Declaring a pointer:
int *ptr; creates a pointer variable named ptr that can store the
address of an integer.
2. Memory allocation:
ptr = new int; allocates memory on the heap for a single integer and
stores its address in the ptr variable.
3. Accessing allocated memory:
*ptr = 10; assigns the value 10 to the memory location pointed to by
ptr.
4. Deallocating memory:
delete ptr; releases the memory previously allocated to ptr back to
the heap.
Important considerations:
# Array allocation: To allocate an array dynamically, use new[] and
delete[].
# Error handling: Always check if the new operation was successful
before using the allocated memory.
# Memory management responsibility: The programmer is
responsible for managing dynamically allocated memory, including
proper deallocation.

(b) What is destructor ? Write a program in C++ that uses


constructors and corresponding destructers.
Ans. A destructor is a special member function that is called
automatically when an object goes out of scope or when we delete
the object with the delete expression.
In C++, a destructor has the same name as that of the class, and it
does not have a return type. ~ precedes the identifier to indicate
destructor.
Characteristics of a Destructor
# A destructor is also a special member function like a constructor.
Destructor destroys the class objects created by the constructor.
# Destructor has the same name as their class name preceded by a
tilde (~) symbol.
# It is not possible to define more than one destructor.
# The destructor is only one way to destroy the object created by the
constructor. Hence, destructor cannot be overloaded.
# It cannot be declared static or const.
# Destructor neither requires any argument nor returns any value.
# It is automatically called when an object goes out of scope.
# Destructor release memory space occupied by the objects created
by the constructor.
# In destructor, objects are destroyed in the reverse of an object
creation.
UNIT – III
6. What is use of inheritance ? Explain the working of
multilevel and hierarchical inheritance with the help of C++
program.
Ans. Inheritance in object-oriented programming (OOP) allows a new
class to "inherit" properties and behaviors from an existing class,
essentially creating a hierarchical relationship where the new class
(derived class) gains the characteristics of the original class (base
class), promoting code reusability and making it easier to build
complex relationships between different types of objects; multilevel
inheritance occurs when a derived class inherits from another
derived class, creating a chain of inheritance, while hierarchical
inheritance happens when multiple derived classes inherit from a
single base class, forming a tree-like structure.
Explanation:
Base Class (Employee):
Defines the basic properties and methods common to all employees
(name, ID, setDetails, displayDetails).
Derived Class (Manager):
Inherits from Employee, adding specific manager details like salary
and methods to manage it (setSalary, displayManagerDetails).
Multilevel Inheritance (SeniorManager):
Inherits from Manager, further extending the hierarchy by adding a
department property and methods to manage it (setDepartment,
displaySeniorManagerDetails).
Hierarchical Inheritance :
Both Manager and other potential derived classes like
"MarketingManager" would inherit from the Employee base class,
creating a hierarchy where each class has its own specific
functionality while sharing common attributes from the parent class.
Key points about inheritance:
Code Reusability:
By inheriting from a base class, you reuse the existing code, reducing
the need to write the same functionality again in derived classes.
Polymorphism:
Inheritance is a foundation for polymorphism, allowing objects of
different classes to be treated as the same type when necessary.
Hierarchical Organization:
Inheritance helps structure your code in a logical hierarchy that
reflects real-world relationships.
7. (a) What is Abstract Class ? Explain by giving suitable C++
programs.
Ans. An abstract class in C++ is a class that cannot be directly
instantiated (you can't create objects of it) and is designed to be used
as a base class for other classes; it contains at least one "pure virtual
function" which forces derived classes to implement the functionality
defined in the abstract class, essentially acting as a blueprint for
defining common behavior across different concrete classes.
Key points about abstract classes:
Pure virtual functions:
A pure virtual function is declared by adding = 0 to the end of its
declaration within the abstract class.
Enforcing implementation:
When a class inherits from an abstract class, it must provide
implementations for all pure virtual functions to be considered a
concrete class.
Purpose:
Abstract classes help to define a common interface and ensure
consistency across different derived classes, promoting code reuse
and polymorphism.
Explanation:
Abstract class 'Shape':
Defines the common interface for all shapes with two pure virtual
functions draw() and getArea().
Derived classes 'Rectangle' and 'Circle':
Each concrete class implements the pure virtual functions from
'Shape' according to their specific shape calculations.
Key point:
You cannot create an object of the 'Shape' class directly because it is
an abstract class. You can only create objects of derived classes that
fully implement the abstract class's functionality.
(b) Compare public and private inheritance by giving
suitable C++ program.
Ans. In C++, "public inheritance" makes the public members of a
base class accessible as public members in the derived class, while
"private inheritance" makes all public and protected members of the
base class private in the derived class, meaning they can only be
accessed through member functions within the derived class itself;
effectively hiding the base class interface from external code.
Explanation:
Public Inheritance:
# In the Employee class, since it inherits Person publicly, you can
directly access name and age from an Employee object and call the
printDetails function as if they were declared within Employee itself.
Private Inheritance:
In the Manager class, because it inherits Person privately, the name
and age members are considered private within Manager. To modify
or access them, you need to use the this pointer to explicitly access
the base class members.
Key points to remember:
Accessibility:
Public inheritance allows direct access to base class members from
derived class objects, while private inheritance hides the base class
interface and requires using accessor functions within the derived
class to access its members.
Polymorphism:
When using public inheritance, you can easily achieve polymorphism
through virtual functions since the derived class can be treated as a
base class object.
Implementation Detail:
Private inheritance is often used when you want to "implement" the
functionality of a base class without exposing its public interface to
external code, effectively creating a "has-a" relationship.
UNIT – IV
8. What is template Function ? What are its features ? Show
the working of template function with the help of program
in C++.
Ans. A "template function" in C++ is a function definition that can
operate on different data types by using a placeholder type
parameter, allowing the compiler to generate specific versions of the
function for each data type used at compile time, essentially creating
a single function that can work with various types without needing to
rewrite the logic for each one; this is a core feature of generic
programming in C++.
Key features of template functions:
Generic type parameter:
A template function uses a placeholder type (like "T") to represent
the data type that will be used when the function is instantiated.
Compile-time instantiation:
When a template function is called with a specific data type, the
compiler generates a new, optimized version of the function tailored
to that data type.
Type deduction:
In many cases, the compiler can automatically deduce the data type
of the arguments passed to a template function, eliminating the need
to explicitly specify the type when calling it.
Flexibility:
Template functions allow you to write code that can work with
various data types like integers, floats, custom classes, etc., without
duplicating the function logic.
Improved code reusability:
By creating a single template function, you can avoid writing separate
functions for each data type, leading to cleaner and more
maintainable code.
#include <iostream>

// Function template to calculate the maximum of two values


template <typename T>
T maximum(T a, T b) {
if (a > b) {
return a;
} else {
return b;
}
}

int main() {
int num1 = 10, num2 = 5;
double num3 = 3.14, num4 = 2.71;

std::cout << "Maximum of " << num1 << " and " << num2 << " is: "
<< maximum(num1, num2) << std::endl;
std::cout << "Maximum of " << num3 << " and " << num4 << " is: "
<< maximum(num3, num4) << std::endl;

return 0;
}
Explanation:
Template declaration:
The line template <typename T> defines a template function named
maximum where T acts as a placeholder for any data type that will
be specified when the function is used.
Function body:
Inside the maximum function, the logic to find the larger value
between a and b is implemented, where both a and b are of type T.
Usage in main function:
# maximum(num1, num2): When this line is called, the compiler
automatically generates a version of the maximum function
specifically for int data type because num1 and num2 are integers.
# maximum(num3, num4): Similarly, the compiler generates a
separate maximum function for double data type to handle the
floating-point values of num3 and num4.
9. Discuss the following in detail with the help of suitable
C++ program.
(i) Template classes.
Ans. Templates are powerful features of C++ that allows us to
write generic programs. There are two ways we can implement
templates:
 Function Templates
 Class Templates

Class Template Declaration


A class template starts with the keyword template followed by
template parameter(s) inside <> which is followed by the class
declaration.
template <class T>
class className {
private:
T var;
... .. ...
public:
T functionName(T arg);
... .. ...
};
In the above declaration, T is the template argument which is a
placeholder for the data type used, and class is a keyword.
Inside the class body, a member variable var and a member
function functionName() are both of type T.

(ii) Exception and derived class.


Ans. An Exception is an unwanted error or hurdle that a program
throws while compiling. There are various methods to handle an
exception which is termed exceptional handling.

Let’s discuss what is Exception Handling and how we catch base and
derived classes as an exception in C++:

# If both base and derived classes are caught as exceptions, then the
catch block of the derived class must appear before the base class.
# If we put the base class first then the derived class catch block will
never be reached. For example, the following C++ code prints
“Caught Base Exception“ .
// C++ Program to demonstrate a catching of
// Derived exception and printing it successfully
#include <iostream>
using namespace std;

class Base {};


class Derived : public Base {};
int main()
{
Derived d;
// Some other functionalities
try {
// Monitored code
throw d;
}
catch (Derived d) {
cout << "Caught Derived Exception";
}
catch (Base b) {
cout << "Caught Base Exception";
}
getchar(); // To read the next character
return 0;
}

You might also like