0% found this document useful (0 votes)
166 views68 pages

BCS 031 Solved Assignment

The document discusses object-oriented programming (OOP) and operators in C++. It defines OOP as an approach that breaks programs into objects with classes, objects, polymorphism, abstraction, encapsulation, and inheritance. The advantages of OOP include reusability, modularity, flexibility, and ease of maintenance. The document then explains various operators in C++ like arithmetic, relational, logical, bitwise, assignment, and other operators with examples.

Uploaded by

Rahul Bhardwaj
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)
166 views68 pages

BCS 031 Solved Assignment

The document discusses object-oriented programming (OOP) and operators in C++. It defines OOP as an approach that breaks programs into objects with classes, objects, polymorphism, abstraction, encapsulation, and inheritance. The advantages of OOP include reusability, modularity, flexibility, and ease of maintenance. The document then explains various operators in C++ like arithmetic, relational, logical, bitwise, assignment, and other operators with examples.

Uploaded by

Rahul Bhardwaj
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/ 68

MY EXAM UPDATES

BCS-031 Programming in C++


Assignment Number :
BCA(3)031/Assignment/2021-22
Question 1:

(a) What is Object Oriented Programming (OOP) approach? Explain advantages of OOP.

ans- OOP stands for Object-Oriented Programming. As you can guess from it’s name it breaks
the program on the basis of the objects in it. It mainly works on Class, Object, Polymorphism,
Abstraction, Encapsulation and Inheritance. Its aim is to bind together the data and functions to
operate on them.

Some of the well-known object-oriented languages are Objective C, Perl, Javascript, Python,
Modula, Ada, Simula, C++, Smalltalk and some Common Lisp Object Standard. Here we are
discussing its benefits on C++.

Benefits of OOP

We can build the programs from standard working modules that communicate with one
another, rather than having to start writing the code from scratch which leads to saving of
development time and higher productivity,

OOP language allows to break the program into the bit-sized problems that can be solved easily
(one object at a time).

The new technology promises greater programmer productivity, better quality of software and
lesser maintenance cost.

OOP systems can be easily upgraded from small to large systems.

It is possible that multiple instances of objects co-exist without any interference,

It is very easy to partition the work in a project based on objects.

It is possible to map the objects in problem domain to those in the program.

1
The principle of data hiding helps the programmer to build secure programs which cannot be
invaded by the code in other parts of the program.

By using inheritance, we can eliminate redundant code and extend the use of existing classes.

Message passing techniques is used for communication between objects which makes the
interface descriptions with external systems much simpler.

The data-centered design approach enables us to capture more details of model in an


implementable form.

While it is possible to incorporate all these features in an OOP, their importance depends upon
the type of project and preference of the programmer. These technology is still developing and
current products may be superseded quickly.

Developing a software is easy to use makes it hard to build.

Disadvantages of OOP

The length of the programmes developed using OOP language is much larger than the
procedural approach. Since the programme becomes larger in size, it requires more time to be
executed that leads to slower execution of the programme.

We can not apply OOP everywhere as it is not a universal language. It is applied only when it is
required. It is not suitable for all types of problems.

Programmers need to have brilliant designing skill and programming skill along withproper
planning because using OOP is little bit tricky.

OOPs take time to get used to it. The thought process involved in object-oriented programming
may not be natural for some people.

Everything is treated as object in OOP so before applying it we need to have excellent thinking
in terms of objects.

(b) Briefly explain different operators of C++.

ans- An operator is a symbol that tells the compiler to perform specific mathematical or
logical manipulations. C++ is rich in built-in operators and provide the following types of
operators −

Arithmetic Operators

2
Relational Operators

Logical Operators

Bitwise Operators

Assignment Operators

Misc Operators

This chapter will examine the arithmetic, relational, logical, bitwise, assignment and
other operators one by one.

Arithmetic Operators

There are following arithmetic operators supported by C++ language −

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

Show Examples

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200

/ Divides numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after an integer division B % A will give


0

++ Increment operator, increases integer value by one A++ will give 11

-- Decrement operator, decreases integer value by one A-- will give 9

3
Relational Operators

There are following relational operators supported by C++ language

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

Show Examples

Operator Description Example

== Checks if the values of two operands are equal or not, if yes then condition
becomes true. (A == B) is not true.

!= Checks if the values of two operands are equal or not, if values are not equal
then condition becomes true. (A != B) is true.

> Checks if the value of left operand is greater than the value of right operand, if
yes then condition becomes true. (A > B) is not true.

< Checks if the value of left operand is less than the value of right operand, if yes
then condition becomes true. (A < B) is true.

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

<= Checks if the value of left operand is less than or equal to the value of right
operand, if yes then condition becomes true. (A <= B) is true.

Logical Operators

There are following logical operators supported by C++ language.

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

Show Examples

4
Operator Description Example

&& Called Logical AND operator. If both the operands are non-zero, then condition
becomes true. (A && B) is false.

|| Called Logical OR Operator. If any of the two operands is non-zero, then


condition becomes true. (A || B) is true.

! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a
condition is true, then Logical NOT operator will make false. !(A && B) is true.

Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &,
|, and ^ are as follows −

Assume if A = 60; and B = 13; now in binary format they will be 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

A = 0011 1100

B = 0000 1101

A&B = 0000 1100

5
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 −

Show Examples

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both operands.
(A & B) will give 12 which is 0000 1100

| Binary OR Operator copies a bit if it exists in either operand. (A | B) will


give 61 which is 0011 1101

^ Binary XOR Operator copies the bit if it is set in one operand but not both.
(A ^ B) will give 49 which is 0011 0001

~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.
(~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed
binary number.

<< Binary Left Shift Operator. The left operands value is moved left by the number
of bits specified by the right operand. A << 2 will give 240 which is 1111 0000

>> Binary Right Shift Operator. The left operands value is moved right by the
number of bits specified by the right operand. A >> 2 will give 15 which is 0000

6
1111

Assignment Operators

There are following assignment operators supported by C++ language −

Show Examples

Operator Description Example

= Simple assignment operator, Assigns values from right side operands to left side
operand. C = A + B will assign value of A + B into C

+= Add AND assignment operator, It adds right operand to the left operand and
assign the result to left operand. C += A is equivalent to C = C + A

-= Subtract AND assignment operator, It subtracts right operand from the left
operand and assign the result to left operand. C -= A is equivalent to C = C - A

*= Multiply AND assignment operator, It multiplies right operand with the left
operand and assign the result to left operand. C *= A is equivalent to C = C * A

/= Divide AND assignment operator, It divides left operand with the right operand
and assign the result to left operand. C /= A is equivalent to C = C / A

%= Modulus AND assignment operator, It takes modulus using two operands and
assign the result to left operand. C %= A is equivalent to C = C % A

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Misc Operators

The following table lists some other operators that C++ supports.

7
Sr.No Operator & Description

sizeof

sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is integer,
and will return 4.

Condition ? X : Y

Conditional operator (?). If Condition is true then it returns value of X otherwise returns
value of Y.

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)

Member operators are used to reference individual members of classes, structures, and

8
unions.

Cast

Casting operators convert one data type to another. For example, int(2.2000) would
return 2.

&

Pointer operator & returns the address of a variable. For example &a; will give actual
address of the variable.

Pointer operator * is pointer to a variable. For example *var; will pointer to a variable
var.

Operators Precedence in C++

Operator precedence determines the grouping of terms in an expression. This affects


how an expression is evaluated. Certain operators have higher precedence than others;
for example, the multiplication operator has higher precedence than the addition
operator −

9
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom. Within an expression, higher precedence operators
will be evaluated first.

Show Examples

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative * / % Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left


10
Comma , Left to right

(c) Explain use of followings in C++ programming, with an


example program for each.

(4 Marks)

(a) for loop

(b) while loop

ans- while loop


Let's first look at the syntax of while loop.

11
while(condition)

statement(s)

while loop checks whether the condition written in ( ) is true or not. If the
condition is true, the statements written in the body of the while loop i.e.,
inside the braces { } are executed. Then again the condition is checked, and
if found true, again the statements in the body of the while loop are
executed. This process continues until the condition becomes false.

An example will make this clear.


#include <iostream>

int main(){

using namespace std;

int n = 1;

while( n <= 10){

cout << n << endl;

n++;

return 0;

12
}

Output

In our example, firstly, we assigned a value 1 to a variable 'n'.

while(n <= 10) - checks the condition 'n <= 10'. Since the value of n is
1 which is less than 10, the statements within the braces { } are
executed.

The value of 'n' i.e. 1 is printed and n++ increases the value of 'n' by 1.
So, now the value of 'n' becomes 2.

Now, again the condition is checked. This time also 'n <= 10' is true
because the value of 'n' is 2. So, again the value of 'n' i.e., 2 gets printed
and the value of 'n' will be increased to 3.

When the value of 'n' becomes 10, again the condition 'n <= 10' is true
and 10 gets printed for the tenth time. Now, n++ increases the value to
'n' to 11.This time, the condition 'n <= 10' becomes false and the
program terminates.

Quite interesting. Isn't it !

for loop

Another type of loop is for loop.

13
Let's go to our first example in which we printed first 10 natural
numbers using while loop. We can also do this with for loop.

Let's look at the syntax of for loop.

for(initialization; condition; propagation)

statement(s)

#include <iostream>

int main(){

using namespace std;

int n;

for( n = 1; n <= 10; n++ ){ cout << n << endl;

return 0;

Output

Now let's see how for loop works.

for(n=1; n<=10; n++)

14
n=1 - This step is used to initialize a variable and is executed first and
only once. Here, 'n' is assigned a value 1.

n<=10 - This is a condition which is evaluated. If the condition is true,


the statements written in the body of the loop are executed. If it is false,
the statement just after the for loop is executed. This is similar to the
condition we used in 'while' loop which was being checked again and
again.

n++ - This is executed after the code in the body of the for loop has
been executed. In this example, the value of 'n' increases by 1 every
time the code in the body of for loop executes. There can be any
expression here which you want to run after every loop.

In the above example, firstly, 'n=1' assigns a value 1 to 'n'.

Then the condition 'n<=10' is checked. Since the value of 'n' is 1,


therefore the code in the body of for loop is executed and thus the
current value of 'n' i.e., 1 gets printed.

Once the codes in the body of for loop are executed, step n++ is
executed which increases the value of 'n' by 1. So now the value of 'n' is
2.

15
Again the condition 'n<=10' is checked which is true because the value
of 'n' is 2. Again codes in the body of for loop are executed and 2 gets
printed and then the value of 'n' is again incremented.

When the value of 'n' becomes 10, the condition 'n <= 10' is true and
10 gets printed. Now, when n++ increases the value to 'n' to 11, the
condition 'n<=10' becomes false and the loop terminates.

Question 2:

(a) What is a class? Explain how a class is created in C++, with the
help of an example.

ans- 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. The private
members are not accessible outside the class; they can be accessed only
through methods of the class. The public members form an interface to
the class and are accessible outside the class.

Instances of a class data type are known as objects and can contain
member variables, constants, member functions, and overloaded
operators defined by the programmer.For Example: Consider the Class
of Cars. There may be many cars with different names and brand but all
of them will share some common properties like all of them will have 4
wheels, Speed Limit, Mileage range etc. So here, Car is the class and

16
wheels, speed limits, mileage are their properties.

A Class is a user defined data-type which has data members and


member functions.A class is defined in C++ using keyword class
followed by the name of class. The body of class is defined inside the
curly brackets and terminated by a semicolon at the end.classes-and-
objects-in-c

Syntax:

ClassName ObjectName;
EXAMPLES
// C++ program to demonstrate
// accessing of data members

#include <bits/stdc++.h>
using namespace std;

17
class Geeks
{
// Access specifier
public:

// Data Members
string geekname;

// Member Functions()
void printname()
{
cout << "Geekname is: " << geekname;
}

};

int main() {

// Declare an object of class geeks Geeks obj1;

// accessing data member


obj1.geekname = "Abhi";

// accessing member function

18
obj1.printname();
return 0;
}
Output:

Geekname is: Abhi

Declaring Objects: When a class is defined, only the specification for the
object is defined; no memory or storage is allocated. To use the data and
access functions defined in the class, you need to create objects.

(b) Explain the following in detail, in context of C++


programming.
i. Access specifies
ii. Friend Function
ans- i. Access modifiers are used to implement an important aspect of
Object-Oriented Programming known as Data Hiding. Consider a real-
life example:

The Research and analysis wing (R&AW), having 10 core members has
come in possession of sensitive confidential information regarding
national security. Now we can correlate these core members to data
members or member functions of a class which in turn can be
correlated to the R&A wing. These 10 members can directly access
confidential information from their wing (the class), but anyone apart
from these 10 members can’t access this information directly i.e.
outside functions other than those prevalent in the class itself can’t
access information that is not entitled to them, without having either
assigned privileges (such as those possessed by friend class and
19
inherited class as will be seen in this article ahead) or access to one of
these 10members who is allowed direct access to the confidential
information (similar to how private members of a class can be accessed
in the outside world through public member functions of the class that
have direct access to private members). This is what data hiding is in
practice.

Access Modifiers or Access Specifiers in a class are used to assign the


accessibility to the class members. That is, it sets some restrictions on
the class members not to get directly accessed by the outside functions.

There are 3 types of access modifiers available in C++:

Public

Private

Protected
Note: If we do not specify any access modifiers for the members inside
the class then by default the access modifier for the members will be
Private.

Let us now look at each one these access modifiers in details:

1. Public: All the class members declared under the public specifier will
be available to everyone. The data members and member functions
declared as public can be accessed by other classes and functions too.
The public members of a class can be accessed fromanywhere in the
program using the direct member access operator (.) with the object of
that class.

20
Example:

// C++ program to demonstrate public

// access modifier

#include<iostream>

using namespace std;

// class definition

class Circle

public:

double radius;

double compute_area()

return 3.14*radius*radius;

};

21
// main function

int main()

Circle obj;

// accessing public datamember outside class

obj.radius = 5.5;

cout << "Radius is: " << obj.radius << "\n";

cout << "Area is: " << obj.compute_area();

return 0;

Output:

Radius is: 5.5

Area is: 94.985

ii. In object-oriented programming, a friend function, that is a "friend"


of a given class, is a function that is given the same access as methods to
private and protected data. [1]

A friend function is declared by the class that is granting access, so


friend functions are part of the class interface, like methods. Friend
22
functions allow alternative syntax to use objects, for instance f(x)
instead of x.f(), or g(x,y) instead of x.g(y). Friend functions have the
same implications on encapsulation as methods.

A similar concept is that of friend class.

Use cases

This approach may be used in friendly function when a function needs


to access private data in objects from two different classes. This may be
accomplished in two similar ways

a function of global or namespace scope may be declared as friend of


both classes

a member function of one class may be declared as friend of another


one.

#include <iostream>

using namespace std;

class Foo; // Forward declaration of class Foo in order for example to


compile.

class Bar {

private:

int a = 0;

public:

23
void show(Bar& x, Foo& y);

friend void show(Bar& x, Foo& y); // declaration of global friend

};

class Foo {

private:

int b = 6;

public:

friend void show(Bar& x, Foo& y); // declaration of global friend

friend void Bar::show(Bar& x, Foo& y); // declaration of friend from


other class

};

// Definition of a member function of Bar; this member is a friend of


Foo

void Bar::show(Bar& x, Foo& y) {

cout << "Show via function member of Bar" << endl;

cout << "Bar::a = " << x.a << endl;

cout << "Foo::b = " << y.b << endl;

// Friend for Bar and Foo, definition of global function

24
void show(Bar& x, Foo& y) {

cout << "Show via global function" << endl;

cout << "Bar::a = " << x.a << endl;

cout << "Foo::b = " << y.b << endl;

int main() {

Bar a;

Foo b;

show(a,b);

a.show(a,b);

(c) Write a C++ program to explain how an object can be


passed as a parameter to a function.
ans- In C++ we can pass class’s objects as arguments and also
return them from a function the same way we pass and return
other variables. No special keyword or header file is required
to do so.

Passing an Object as argument

To pass an object as an argument we write the object name as


25
the argument while calling the function the same way we do it
for other variables.
Syntax:

function_name(oject_name);
Example: In this Example there is a class which has an integer
variable ‘a’ and a function ‘add’ which takes an object as
argument. The function is called by one object and takes
another as an argument. Inside the function, the integer value
of the argument object is added to that on which the ‘add’

26
function is called. In this method, we can pass objects as an
argument and alter them.

// C++ program to show passing


// of objects to a function

#include <bits/stdc++.h>
using namespace std;

class Example {public:


int a;

// This function will take


// an object as an argument
void add(Example E)
{

a = a + E.a;
}
};

27
// Driver Code
int main()
{

// Create objects
Example E1, E2;

// Values are initialized for both objects


E1.a = 50;
E2.a = 100;

cout << "Initial Values \n";


cout << "Value of object 1: " << E1.a
<< "\n& object 2: " << E2.a
<< "\n\n"; // Passing object as an argument
// to function add()
E2.add(E1);

28
// Changed values after passing
// object as argument
cout << "New values \n";
cout << "Value of object 1: " << E1.a

<< "\n& object 2: " << E2.a


<< "\n\n";

return 0;
}
Output
Initial Values
Value of object 1: 50

& object 2: 100


Question 3:
(a) What are containers? Explain use of List container
class, with the help of an example.
ans-A container stores many entities and provide sequential or direct
access to them. List, vector and strings are such containers in standard
template library. The string class is a container that holds chars. All
container classes access the contained elements safely and efficiently by
using iterators. Container class is a class that hold group of same or
mixed objects in memory. It can be heterogeneous and homogeneous.

29
Heterogeneous container class can hold mixed objects in memory
whereas when it is holding same objects, it is called as homogeneous
container class.

What is a container class? What are the types of container classes?

A class is said to be a container class which is utilized for the purpose of


holding objects in memory or persistent media. A generic class plays a
role of generic holder. A container class is a good blend of predefined
behavior and an interface that is well known. The purpose of container
class is to hide the topology for the purpose of objects list maintenance
in memory. A container class is known as heterogeneous container,
when it contains a set of different objects. A container class is known as
homogeneous container when it contains a set of similar objects.

What is container class? Explain containers of pointer.

- Container class is one of the classes that were put into class libraries.
To handle objects that contain other objects, container classes are used.
A GUI class library contains a group of container classes.

- Containers of pointers provide containers to hold the objects that are


heap-allocated in manner that is exception-safe and with minimum
overhead. The central idea is to make OOP easier in C++. This is done
by establishing a standard a set of classes, methods to deal with OO
specific problems.

What are the C++ standardized container classes?

The following are the standardized container classes :

1. std::map :

Used for handle sparse array or a sparse matrix.

2. std::vector :

Like an array, this standard container class offers additional features

30
such as bunds checking through the at () member function, inserting or
removing elements, automatic memory management and throwing
exceptions.

std::string :

A better supplement for arrays of chars.

Consider some examples:

void f(int a[], int s)

// do something with a; the size of a is s

for (int i = 0; i<s; ++i) a[i] = i;

int arr1[20];

int arr2[10];

void g()

f(arr1,20);

f(arr2,20);

(b) What is inheritance? What are different types of


inheritance? Explain how multiple
inheritance is implemented in C++, with the help of a

31
program.
ans-The capability of a class to derive properties and characteristics
from another class is called Inheritance. Inheritance is one of the most
important feature of Object Oriented Programming.

Sub Class: The class that inherits properties from another class is called
Sub class or Derived Class.

Super Class:The class whose properties are inherited by sub class is


called Base Class or Super class. Why and when to use inheritance?

Consider a group of vehicles. You need to create classes for Bus, Car and
Truck. The methods fuelAmount(), capacity(), applyBrakes() will be
same for all of the three classes. If we create these classes avoiding
inheritance then we have to write all of these functions in each of the
three classes as shown in below figure:

You can clearly see that above process results in duplication of same
code 3 times. This increases the chances of error and data redundancy.
To avoid this type of situation, inheritance is used. If we create a class
Vehicle and write these three functions in it and inherit the rest of the
classes from the vehicle class, then we can simply avoid the duplication
of data and increase re-usability. Look at the below diagram in which
the three classes are inherited from vehicle class:

32
Using inheritance, we have to write the functions only one time instead
of three times as we have inherited rest of the three classes from base
class(Vehicle).
Implementing inheritance in C++: For creating a sub-class which is
inherited from the base class we have to follow the below syntax.
Syntax:

class subclass_name : access_mode base_class_name


{
//body of subclass
};
Here, subclass_name is the name of the sub class, access_mode is the
mode in which you want to inherit this sub class for example: public,
private etc. and base_class_name is the name of the base class from
which you want to inherit the sub class.
Note: A derived class doesn’t inherit access to private data members.
However, it doesinherit a full parent object, which contains any private
members which that class declares.

33
// C++ program to demonstrate implementation
// of Inheritance

#include <bits/stdc++.h>
using namespace std;

//Base class
class Parent
{
public:
int id_p;};

// Sub class inheriting from Base Class(Parent)


class Child : public Parent
{
public:
int id_c;
};

//main function
int main()
{

34
Child obj1;

// An object of class child has all data members


// and member functions of class parent
obj1.id_c = 7;
obj1.id_p = 91;
cout << "Child id is " << obj1.id_c << endl;
cout << "Parent id is " << obj1.id_p << endl;

return 0;
}
Output
Child id is 7
Parent id is 91

Types of Inheritance in C++

35
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.

Syntax:

class subclass_name : access_mode base_class


{
//body of subclass
};
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.

Syntax:

class subclass_name : access_mode base_class1, access_mode


base_class2, ....
{

36
//body of subclass
};3. Multilevel Inheritance: In this type of inheritance, a derived class is
created from another derived class.
C++ Multiple Inheritance Example
Here is a simple example illustrating the concept of C++ multiple
inheritance.

// multiple inheritance.cpp
#include
using namespace std;
class A
{
public:
int x;
void getx()
{
cout << "enter value of x: "; cin >> x;
}
};
class B
{
public:
int y;
void gety()

37
{
cout << "enter value of y: "; cin >> y;
}
};
class C : public A, public B //C is derived from class A and class B
{
public:
void sum()
{
cout << "Sum = " << x + y;
}
};

int main()
{
C obj1; //object of derived class C
obj1.getx();
obj1.gety();
obj1.sum();
return 0;
} //end of program
Output

38
enter value of x: 5
enter value of y: 4
Sum = 9
Explanation

In the above program, there are two base class A and B from which class
C is inherited. Therefore, derived class C inherits all the public members
of A and B and retains their visibility. Here, we have created the object
obj1 of derived class C.

(c) Write a C++ program to overload ‘+’ operator in such a


way that it return the sum of lengths of two strings (Note: if
S1 and S2 are two strings then S1+S2 or S2 + S1 should
give the
sum of lengths of S1 and S2).
ans- Given two strings. The task is to concatenate the two
strings using Operator Overloading in C++.

Example:

Input: str1 = "arpit", str2 = “gochar"


Output: arpitgochar

Input: str1 = "gochar", str2 = "arpit"


Output: gochararpit
examples
39
// C++ Program to concatenate two string
// using unary operator overloading
#include <iostream>
#include <string.h>

using namespace std;

// Class to implement operator overloading


// function for concatenating the strings
class AddString {

public:
// Classes object of string
char s1[25], s2[25];

// Parameterized Constructor
AddString(char str1[], char str2[])
{
// Initialize the string to class object
strcpy(this->s1, str1);
strcpy(this->s2, str2); }

40
// Overload Operator+ to concat the string
void operator+()
{
cout << "\nConcatenation: " << strcat(s1, s2);
}
};

// Driver Code
int main()
{
// Declaring two strings
char str1[] = "arpit";
char str2[] = "gochar";

// Declaring and initializing the class


// with above two strings
AddString a1(str1, str2);

// Call operator function


+a1;

41
return 0;
}
output:
Concatenation: arpitgochar

Question 4:
(a) Explain the following in detail with the help of
examples, in context of C++ programming
(9 Marks)
i. Destructor
ii. Virtual Function
iii. Inline function
ans- Destructor is an instance member function which is
invoked automatically whenever an object is going to be
destroyed. Meaning, a destructor is the last function that is
going to be called before an object is destroyed.

The thing is to be noted here, if the object is created by using


new or the constructor uses new to allocate memory which
resides in the heap memory or the free store, the destructor
should use delete to free the memory.

Syntax:

~constructor-name();

42
Properties of Destructor:

Destructor function is automatically invoked when the objects


are destroyed.
It cannot be declared static or const.
The destructor does not have arguments.
It has no return type not even void.
An object of a class with a Destructor cannot become a member
of the union.
A destructor should be declared in the public section of the
class.
The programmer cannot access the address of destructor.
ii.A virtual function is a member function which is declared
within a base class and is re-defined(Overriden) 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.

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 Run-time.Rules for

43
Virtual Functions
Deleting a derived class object using a pointer of base class
type that has a non-virtual destructor results in undefined
behavior. To correct this situation, the base class should be
defined with a virtual destructor. For example, following
program results in undefined behavior.

// CPP program without virtual destructor


// causing undefined behavior
#include<iostream>

using namespace std;


// CPP program without virtual destructor
// causing undefined behavior
#include<iostream>

using namespace std;

class base {
public:
base()
{ cout<<"Constructing base \n"; }

44
~base()
{ cout<<"Destructing base \n"; }
};

class derived: public base {


public:
derived()
{ cout<<"Constructing derived \n"; }
~derived()
{ cout<<"Destructing derived \n"; }
};

int main(void)
{
derived *d = new derived();
base *b = d;
delete b;
getchar();
return 0;
}
output:

45
Constructing base
Constructing derived
Destructing base
iii. Inline function and classes:
When the program executes the function call instruction the CPU stores
the memory address of the instruction following the function call,
copies the arguments of the function on the stack and finally transfers
control to the specified function. The CPU then executes the function
code, stores the function return value in a predefined memory
location/register and returns control to the calling function. This can
become overhead if the execution time of function is less than the
switching time from the caller function to called function (callee). For
functions that are large and/or perform function to called function
(callee).. It is also possible to define the inline function inside the class.
In fact, all the functions defined inside the class are implicitly inline.
Thus, all the restrictions of inline functions are also applied here. If you
need to explicitly declare inline function in the class then just declare
the function inside the class and define it outside the class using inline
keyword.
For example:

class S
{
public:
inline int square(int s) // redundant use of inline
{ // this function is automatically inline
// function body

46
}
};
The above style is considered as a bad programming style. The best
programming style is to just write the prototype of function inside the
class and specify it as an inline in the function definition.
For example:

class S
{
public:
int square(int s); // declare the function
};

inline int S::square(int s) // use inline prefix


{

47
(b) What is template? Write appropriate statements to create a
template class for Stack data

Structure in C++.

ans- Templates are a feature of the C++ programming language


that allows functions and classes to operate with generic types.
This allows a function or class to work on many different data
types without being rewritten for each one.

There are three kinds of templates: function templates, class


templates and variable templates.

#include<iostream.h>

/* Define default capacity of stack */

48
#define SIZE 10

/* Class for stack */

template <class T>

class stack

private:

T *array;

int top;

int capacity;

public:

stack(int size = SIZE);// constructor

void push(T);

T pop();

};

/* Constructor to initialize stack */

template <class T>

stack<T>::stack(int size)

49
array = new T[size];

top = -1;

capacity = size;

/* Function to insert an element into the stack */

template <class T>

void stack<T>::push(T value)

if (top == (capacity-1))

cout << "Stack Overflow" << endl;

else

cout << "Inserting " << value << endl;

array[++top] = value;

/* Function to pop top element from the stack */

50
template <class T>

T stack<T>::pop()

/* check for stack underflow */

if (top == -1)

cout << "Stack UnderFlow" << endl;

return 0;

else

cout << "Removing " << array[top] << endl;

/* Decrease stack size by 1 and (optionally) return the popped


element */

return array[top--];

// main function

51
void main()

int retn;

stack<int> obj(2);

obj.push(10);

obj.push(20);

retn = obj.pop();

retn = obj.pop();

obj.push(30);

retn = obj.pop();

Output

Inserting 10

Inserting 20

Removing 20

Removing 10

Inserting 30

52
Removing 30

Question 5:

(a) What is exception? How exceptions are handled in C++?


Write program to handle stack

overflow as exception

ans- Exceptions are run-time anomalies or abnormal conditions


that a program encounters during its execution. C++ provides
following specialized keywords for this purpose.

try - Represents a block of code that can an exception.

catch - Represents a block of code that is executed when a


particular exception is thrown.

throw - Used to throw an exception. Also used to list the


exceptions that a function throws, but doesn’t handle itself.

Advantages of Exception Handling

Separation of Error Handling code from Normal Code - In


traditional error handling codes, there are always if else

53
conditions to handle errors. These conditions and the code to
handle errors get mixed up with the normal flow. This makes the
code less readable and maintainable. With try catch blocks, the
code for error handling becomes separate from the normal flow.

Functions/Methods can handle any exceptions they choose - A


function can throw many exceptions, but may choose to handle
some of them. The other exceptions which are thrown, but not
caught can be handled by caller. If the caller chooses not to catch
them, then the exceptions are handled by caller of the caller.

In C++, a function can specify the exceptions that it throws using


the throw keyword. The caller of this function must handle the
exception in some way (either by specifying it again or catching it)
using System;

public class Example

private const int MAX_RECURSIVE_CALLS = 1000;

static int ctr = 0;

public static void Main()

54
{

Example ex = new Example();

ex.Execute();

Console.WriteLine("\nThe call counter: {0}", ctr);

private void Execute()

ctr++;

if (ctr % 50 == 0)

Console.WriteLine("Call number {0} to the Execute method",


ctr);

if (ctr <= MAX_RECURSIVE_CALLS)

Execute();

ctr--;

55
// The example displays the following output:

// Call number 50 to the Execute method

// Call number 100 to the Execute method

// Call number 150 to the Execute method

// Call number 200 to the Execute method

// Call number 250 to the Execute method

// Call number 300 to the Execute method

// Call number 350 to the Execute method

// Call number 400 to the Execute method

// Call number 450 to the Execute method

// Call number 500 to the Execute method

// Call number 550 to the Execute method

// Call number 600 to the Execute method

// Call number 650 to the Execute method

// Call number 700 to the Execute method

// Call number 750 to the Execute method

// Call number 800 to the Execute method

// Call number 850 to the Execute method

// Call number 900 to the Execute method

56
// Call number 950 to the Execute method

// Call number 1000 to the Execute method

//

// The call counter: 0

(b) What is function overloading? Write a C++ program to


explain concept of function

overloading.

ans- Function overloading is a C++ programming feature that


allows us to have more than one function having same name but
different parameter list, when I say parameter list, it means the
data type and sequence of the parameters, for example the
parameters list of a function myfuncn(int a, float b) is (int, float)
which is different from the function myfuncn(float a, int b)
parameter list (float, int). Function overloading is a compile-time
polymorphism.

Now that we know what is parameter list lets see the rules of
overloading: we can have following functions in the same scope.

sum(int num1, int num2)

sum(int num1, int num2, int num3)

sum(int num1, double num2)

57
The easiest way to remember this rule is that the parameters
should qualify any one or more of the following conditions, they
should have different type, number or sequence of parameters.

For example:

These two functions have different parameter type:

sum(int num1, int num2)

sum(double num1, double num2)

These two have different number of parameters:

sum(int num1, int num2)

sum(int num1, int num2, int num3)

These two have different sequence of parameters:

sum(int num1, double num2)

sum(double num1, int num2)

All of the above three cases are valid case of overloading. We can
have any number of functions, just remember that the parameter
list should be different. For example:

58
int sum(int, int)

double sum(int, int)

This is not allowed as the parameter list is same. Even though they
have different return types, its not valid.

Function overloading Example

Lets take an example to understand function overloading in C++.

#include <iostream>

using namespace std;


class Addition {

public:

int sum(int num1,int num2) {

return num1+num2;

int sum(int num1,int num2, int num3) {

return num1+num2+num3;

59
};

int main(void) {

Addition obj;

cout<<obj.sum(20, 15)<<endl;

cout<<obj.sum(81, 100, 10);

return 0;

Output:

35

191

(c) Explain use of any two I/O formatting flags in C++ with
example.

ans- C++ defines some format flags for standard input and output,
which can be manipulated with the flags(), setf(), and unsetf()
functions. For example,

cout.setf(ios::left);Few standard ios class functions are:

width(): The width method is used to set the required field width.

60
The output will be displayed in the given width

precision(): The precision method is used to set the number of the


decimal point to a float value

fill(): The fill method is used to set a character to fill in the blank
space of a field

setf(): The setf method is used to set various flags for formatting
output

unsetf(): The unsetf method is used To remove the flag setting

Working:

#include<bits/stdc++.h>

using namespace std;

// The width() function defines width

// of the next value to be displayed

// in the output at the console.void IOS_width()

cout << " \n";

cout << "Implementing ios::width\n\n";

61
char c = 'A';

// Adjusting width will be 5.

cout.width(5);

cout << c <<"\n";

int temp = 10;

// Width of the next value to be

// displayed in the output will

// not be adjusted to 5 columns.

cout<<temp;

cout << "\n \n";

void IOS_precision()

62
{cout << "\n \n";

cout << "Implementing ios::precision\n\n";

cout << "Implementing ios::width";

cout.setf(ios::fixed, ios::floatfield);

cout.precision(2);

cout<<3.1422;

cout << "\n \n";

// The fill() function fills the unused

// white spaces in a value (to be printed

// at the console), with a character of choice.

void IOS_fill()

cout << "\n \n";

cout << "Implementing ios::fill\n\n";

char ch = 'a';

// Calling the fill function to fill

63
// the white spaces in a value with a

// character our of choice.

cout.fill('*');

cout.width(10);

cout<<ch <<"\n";cout<<ch <<"\n";

int i = 1;

// Once you call the fill() function,

// you don't have to call it again to

// fill the white space in a value with

// the same character.

cout.width(5);

cout<<i;

cout << "\n \n";

64
void IOS_setf()

cout << "\n \n";

cout << "Implementing ios::setf\n\n";

int val1=100,val2=200;

cout.setf(ios::showpos);

cout<<val1<<" "<<val2;

cout << "\n \n";

void IOS_unsetf()

cout << "\n \n";

cout << "Implementing ios::unsetf\n\n";

cout.setf(ios::showpos|ios::showpoint);

// Clear the showflag flag without

// affecting the showpoint flag

cout.unsetf(ios::showpos);

cout<<200.0;

cout << "\n \n";

65
}

// Driver Method

int main()

IOS_width();

IOS_precision;

IOS_fill();

IOS_setf();

IOS_unsetf();

return 0;

Output:

--------------------------Implementing ios::width

10

66
Implementing ios::fill

*********a

****1

Implementing ios::setf

+100 +200

Implementing ios::unsetf

200.000

67
68

You might also like