BCS031
BCS031
Ans.
implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main
aim of OOP is to bind
together the data and the functions that operate on them so that no other part of the code can
access this data except that
function.
Features of OOP:
1. Inheritance: In layman's terms, the attributes that you inherit from your parents are a simple
illustration of inheritance. Classes may inherit characteristics from other classes thanks to
inheritance. Parent classes, in other words, extend properties and behaviors to child classes.
Reusability is aided via inheritance. Prototyping is another name for inheritance in JavaScript. A
prototype abject serves as a base from which another object may derive its features and actions.
Thus, you may use multiple prototype abject templates to form a prototype chain. Inheritance is
passed down from one generation to the next. parent
2. Encapsulation: Encapsulation is the process of enclosing all eritical information inside an object
and only revealing a subset of it to the outside world. For example, code inside the class template
defines attributes and behaviors. The data and methods are then enclosed in the object when it is
created from the class. Inside a class, encapsulation conceals the underlying software code
implementation and the internal data of the objects. Encapsulation necessitates designating certain
fields as private while others are made public.
3. Abstraction: Abstraction refers to the user's interaction with just a subset of an object's
characteristics and operations. To access a complicated item, abstraction uses simpler, high-level
technigues.
4. Polymorphism: Polymorphism refers to the creation of items that have similar behavior, For
example, objects may override common parent behaviors with particular child behaviors through
inheritance. Method overriding and method overloading are two ways that polymorphism enables
the same method to perform various actions.
5. Objects: An object is a self-contained segment with the attributes and processes needed to make
data usable in programming terms. From an object-oriented perspective, objects are the main
building pieces of programs. In each application you create, you may employ a variety of objects of
various sorts, Each kind of object is derived from a specific class of that type. Consider an object to
be a sculpt of the real-world perceptions, processes, or objects that are important to the application
you're designing.
6. Classes: In the oops concept, a class is a construct that is used to describe an individual type. The
class is instantiated into
instances of itself — referred to as class instances or simply objects. A class defines ingredient
members that allow its instances to
have position and behavior. Member variables or instance variables facilitate a class instance to
maintain its position. On the
other hand, other kinds of members, especially methods, allow the behavior of class instances.
Simply classes consequently
define the type of their instances. A class usually represents a person, place or thing, or something.
Ans. C++ has many built-in operator types and they are classified as follows:
* Unary Operators: Operators that operates or works with a single operand are unary operators. For
example: (++, -)
* Binary Operators: Operators that operates or works with two operands are binary operators. For
example: (+,—, *, /)
2. Relational Operators: These are used for comparison of the values of two operands. For example,
checking if one operand is
equal to the other operand or not, an operand is greater than the other operand or not etc. Some of
the relational operators are
3. Logical Operators: Logical Operators are used to combine two or more conditions/constraints or to
complement the
evaluation of the original condition in consideration. The result of the operation of a logical operator
is a boolean value either
true or false. For example, the logical AND represented as ‘&&’ operator in C or C++ returns true
when both the conditions
under consideration are satisfied. Otherwise it returns false. Therefore, a &8& b returns true when
both a and b are true (i.e. non-
zero).
4. Bitwise Operators: The Bitwise operators is used to perform bit-leve| operations on the operands:
The operators are first
converted to bit-level and then the calculation is performed on the operands. The mathematical
operations such as addition,
subtraction, multiplication etc. can be performed at bit-level for faster processing. For example, the
bitwise AND represented as & operator in C or C++ takes two numbers as operands and does AND on
every bit of two numbers. The result of AND is 1 only
5. Assignment Operators: Assignment operators are used to assign value to a variable. The left side
operand of the assignment
operator is a variable and right side operand of the assignment operator is a value. The value on the
right side must be of the
same data-type of variable on the left side otherwise the compiler will raise an error.
6. Other Operators: Apart from the above operators there are some other operators available in C or
C++ used to perform some
used to compute the size of its operand. The result of sizeof is of unsigned integral type which is
usually denoted by size_t.
(b) Comma Operator: The comma operator (represented by the token ,) is a binary operator that
evaluates its first operand and
discards the result, it then evaluates the second operand and returns this value (and type). The
comma operator has the lowest
(c) Conditional Operator: Conditional operator is of the form Expressionl ? Expression2 : Expression3
. Here, Expression is the
condition to be evaluated. If the condition(Expressionl) is True then we will execute and return the
result of Expression2
otherwise if the condition(Expressionl) is false then we will EE and return the result of Expression3.
We may replace the
(c) Explain use of followings in C++ programming, with EY program for each.
(a) ::
(c) 2:
Ans. (a) :: The scope resolution operator is the highest precedence operator in the C++ language. The
scope resolution operator
Example:
#include<iostream>
int x; // Global x
int main()
intx=10; // Local x
return 0;
Output:
Value of local x is 10
(b) for loop: This is a repetition control structure that helps us iterate over a section of C++ code for a
fixed number of times. A
for loop runs provided the test expression is true. The loop terminates execution immediately the
test expression becomes false.
This means before the execution of the loop body in each iteration, the condition has to be
evaluated. If the evaluation returns a
true, the loop body is executed. If the evaluation returns a false, execution of the loop body is
terminated.
C++ statement(s);
Example:
#include <iostream>
int main()}{
}
return 0;
Output:
(c) ?: The conditional operator evaluates an expression, returning one value if that expression
evaluates to true, and a different
Example:
// conditional operator
#include <iostream>
int main ()
int a,b,c;
a=2; roy
c=(a>b)?a:b;
Ans.
#include <iostream>
int main(}{
}
[* adding corresponding elements of both matrices
ii fir
return 0;
Output:
33
123
456
789
654
321
10 10 10
10 10 10
10 10 10
i. Abstract class
Ans. i. Abstract class: An abstract class in C++ is a class that has at least one pure virtual function (i.e.,
a function that has no
definition). The classes inheriting the abstract class must provide a definition for the pure virtual
function; otherwise, the
Abstract classes are essential to providing an abstraction to the code to make it reusable and
extendable.
Example:
#include <iostream>
class Shape {
public:
width = w;
void setHeight(int h) {
height = h;
protected:
int width;
int height;
public:
int Area() {
b “oo
public:
int Area) {
int main() {
Rectangle R;
Triangle T;
R.setWidth(5);
R.setHeight(10);
T.setWidth(20});
T.setHeight(8);
cout << "The area of the rectangle is: " << R.Area() << endl;
cout << "The area of the triangle is: " << T.Area() << endl;
Output:
ii. Order of constructer calling in inheritance: When we derive a class from the base class then all the
data members of the base
class will become a member of the derived class. We use the constructor to initialize the data
members and here the obvious
case is when the data is inherited into the derived class who will be responsible to initialize them? To
initialize the inherited data
membres constructor is necessary and that's why the constructor of the base class is called first. In
the program given below, we
example:
#include <iostream>
class Base
int x;
// default constructor
Base()
1 STUDY
inty;
public:
// default constructor
Derived()
// parameterized constructar
Derived(int i)
int main()
Base b;
Derived di;
Derived d2(10};
Output:
(c) Write a C++ program to explain how an object can be passed as a parameter to a function.
Ans
#include <iostream>
class A {
public:
char ch = 'A'
} fe =
int main() { J 2d
A obj;
obj.display(obj);
return 0;
Output
Age =20
Character = A
Q3. (a) What are containers? Explain any two container classes of C++.
Ans. A container is a holder object that stores a collection of other objects (its elements). They are
implemented as class
The container manages the storage space for its elements and provides member functions to access
them, either directly or
Sequence containers: In C++, sequential containers allow us to store elements that can be accessed
in sequential order.
Internally, sequential containers are implemented as arrays or linked lists data structures.
Example:
#include <iostream>
ffinclude <vector>
int main() {
return 0;
Output:
Associative containers: In C++, associative containers allow us to store elements in sorted order. The
order doesn’t depend upon
when the element is inserted. Internally, they are implemented as binary tree data structures.
Example:
#include <iostream>
#Hinclude <set>
int main() {
nom,
return 0;
Output:
(b) What is inheritance? What are different types of inheritance supported by C++? Explain
advantage of inheritance with the
help of a program.
Ans. Inheritance :- 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. When creating a class, instead of writing completely new data
members and member functions, the programmer can designate that the new class should inherit
the members of an existing class. This existing class is called the base class, and the new class is
referred to as the derived class.
1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one class. i.e. one
sub class is inherited by one base class only.
2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit from more
than one classes. i.e one sub class is inherited from more than one base classes.
3. Multilevel Inheritance: In this type of inheritance, a derived class is created from another derived
class.
4. Hierarchical Inheritance: In this type of inheritance, more than one sub class is inherited from a
single base class. i.e. more than one derived class is created from a single base class.
5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more than one type
of inheritance. For
Advantages of inheritance:
* [nheritance promotes reusability. When a class inherits or derives another class, it can access all
the functionality of
inherited class.
s Reusability enhanced reliability. The base class code will be already tested and debugged.
* As the existing code is reused, it leads to less development and maintenance costs.
// in single inheritance
#include <iostream>
// base class
class Parent
public:
Parent()
// sub class
= =a
public:
as)
J/ main function
int main() {
Child obj;
return 0;
Output:
(c) What is operator overloading in C++? Explain use of operator overloading with the help of a
program to add two real
numbers.
Ans. Operator overloading: In C++, we can make operators work for user-defined classes. This means
C++ has the ability to provide the operators with a special meaning for a data type, this ability is
known as operator overloading. For example, we can overload an operator ‘+ in a class like String so
that we can concatenate two strings by just using +, Other example classes where arithmetic
operators may be overloaded are Complex Numbers, Fractional Numbers, Big Integer, etc. Operator
overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing
operator in C++ without changing its original meaning.
#include<jostream>
using namespace std; £, ChE \
=K
class Complex {
private:
public:
Complex res;
return res;
void print() { cout << real <<" +i" << imag << '\n"; }
kb
int main()
c3.print{);
Output:
12 + i9
Q4. (a) Explain the following in detail with the help of examples, in context of C++ programming
Ans. i. Object and Class: An Object is an instance of a Class. When a class is defined, no memory is
allocated but when it is
Class: A class in C++ is the building block that leads to Object-Oriented programming. It is a user-
defined data type, which holds
its own data members and member functions, which can be accessed and used by creating an
instance of that class. A C++ class
For Example: Consider the Class of Cars. There may be many cars with different names and brand but
all of them will share some
commaon properties like all of them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car
is the class and wheels,
* A (Classis a user defined data-type which has data members and member functions.
* Data members are the data variables and member functions are the functions used to manipulate
these variables and
together these data members and member functions defines the properties and behavior of the
objects in a Class.
* Inthe above example of class Car, the data member will be speed limit, mileage etc and member
functions can be apply
Example:
class
// Access specifier
public:
// Data Members
string ignoustudyhelpername;
// Member Functions()
void printname()
int main() {
ignoustudyhelper objl;
objl.printname();
return 0;
Output;
* A C++ virtual function is a member function in the base class that you redefine in a derived class. It
is declared using the
virtual keyword.
* It is used to tell the compiler to perform dynamic linkage or late binding on the function.
* There is a necessity to use the single pointer to refer to all the objects of the different classes. So,
we create the pointer
to the base class that refers to all the derived objects. But, when base class pointer contains the
address of the derived
class object, always executes the base class function, This issue can only be resolved by using the
'virtual' function.
When the function is made virtual, C++ determines which function is to be invoked at the runtime
based on the type of
Example:
#include <iostream>
class A
{
int x=5;
public:
void display()
class B: public A
inty = 10;
public:
void display()
ki
int main()
A *a;
Bb;
a=8&b;
a->displayl();
return 0;
Output:
Value of xis: 5 Wm
iii. Friend function: If a function is defined as a friend function in C++, then the protected and private
data of a class can be
By using the keyword friend compiler knows the given function is a friend function.
For accessing the data, the declaration of a friend function should be done inside the body of a class
starting with the keyword
friend.
Example:
#include <iostream>
class Box
private:
int length;
public:
Box(): length{0) { }
int printLength(Box b)
b.length += 10;
return b.length;
int main()
Box b; Am pal 4
Output:
Length of box : 0
iv. 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 generally. The constructor in C++ has the same name as
the class or
structure, Constructor is invoked at the time of object creation. It constructs the values i.e, provides
data for the object which is
Constructor does not have a return value, hence they do not have a return type.
Example:
#include <iostream>
class student {
int rno;
char name[10];
double fee;
public:
student()
void display()
cout << endl << ro << "\t" << name << "\t" << fee;
int main()
s.display();
return 0;
Output:
0 6.95303e-310
(b) What is template? Write appropriate statements to create a template class for Queue data
Structure in C++.
Ans. A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as
a parameter so that we
don’t need to write the same code for different data types. For example, a software company may
need sort() for different data
types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data
type as a parameter. ++ adds two new keywords to support templates: ‘template’ and ‘typename’.
The second keyword can always be replaced by
keyword ‘class’.
#include <iostream>
#include <cstdlib>
#define SIZE 10
class queue
int front; // front points to front element in the queue (if any)
public:
X peek();
int size();
bool isEmpty};
bool isFull();
queue<X>::queue(int size)
capacity = size;
front =0;
rear =-1;
count =0;
void queue<X>::dequeue()
if (isEmpty(})
{
cout << "UnderFlow\nProgram Terminated\n";
exit(EXIT_FAILURE);
count--;
if (isFull())
exit(EXIT_FAILURE);
arr[rear] = item;
count++; Wome fl
X queue<X>::peek()
if (isEmpty())
exit(EXIT_FAILURE);
return arr{front];
int queue<X>:size()
return count;
bool queue<X>::isEmpty()
bool queue<X>::isFull()
{
return (size() == capacity);
int main()
queue<string> qi4);
g.enqueue("a");
q.enqueue("b");
g.enqueue("c");
cout << "Front element is: " << g.peek() << endl;
g.dequeue();
q.enqueue("d"); (=)
nf
g.dequeue();
g.dequeue();
g.dequeue();
if (g.isEmptyl))
else
return 0;
}
Output:
Inserting a
Inserting b
Inserting c
Removing a
Inserting d
Queue size is 3
Removing b
Remaving c
Removing d
Queue Is Empty
Q5. (a) What is exception? What is need of exceptions handling in C++? Write program to handle
arithmetic as exception in
Ans. An exception is a problem that arises during the execution of a program. A C++ exception is a
response to an exceptional
circumstance that arises while a program is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C++ exception
handling is built upon three keyword: try, catch, and throw.
* throw - rogram throws an exception when a problem shows up. This is done using a throw
keyword.
*catch - A program catches an exception with an exception handler at the place in a program where
you want to handle
catch blocks.
Program:
#include <iostream>
int main()
int x=-1;
// Some code
try {
if (x <0)
throw x;
catch (int x) {
return 0;
}
Output:
Before try
Inside try
Exception Caught
(b) What is function overriding? Write a C++ program to explain concept of function overriding.
When a function name is overloaded with different jobs it is called Function Overloading. In Function
Overloading “Function”
name should be the same and the arguments should be different. Function overloading can be
considered as an example of
Program:
#include <iostream>
void print(int i) {
print(10); ee
print{10.10);
print{"ten");
return 0;
Output:
Here is int 10
(c) Explain how I/O formatting is done in C++ with the help of a program.
Ans.C++ helps you to format the I/O operations like determining the number of digits to be displayed
after the decimal point,
Program:
#include <iostream>
#finclude <fstream>
cout.width(5);
cout.width(5);
cout. fill{('*');
cout.precision(5);
cout.setf(ios::showpos);
cout.unsetf{ios::showpos);
Output: