OBJECT ORIENTED PROGRAMMING USING C+++
OBJECT ORIENTED PROGRAMMING USING C+++
MAY – 2024
int num2 = 5;
}
if-else statement.
Code
if (num % 2 == 0) {
} else {
}
switch-case statement.
Code
switch (grade) {
case 'A':
break;
case 'B':
break;
default:
}
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) {
count++;
}
do-while loop.
Code
int num = 0;
do {
num++;
}
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.
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
−
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.
B = 0000 1101
-----------------
~A = 1100 0011
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.
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 −
int main() {
int numbers[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
cout << "Element at row 1, column 2: " << numbers[1][1] << endl;
// Outputs: 6
}
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;
age = 0;
};
int main() {
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:
length = l;
width = w;
};
int main() {
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;
name = other.name;
salary = other.salary;
};
int main() {
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>
*ptr = 10;
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.
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
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;