0% found this document useful (0 votes)
516 views37 pages

BCS 31

The document discusses (a) comparing structured and object-oriented programming, (b) inline functions and their advantages over normal functions, (c) passing objects as arguments to functions with an example, (d) the properties of friend functions, (e) the differences between constructors and automatic initialization and what copy constructors are, and (f) what function overloading is and how function calls are matched to overloaded functions with an example.

Uploaded by

Ls Payne
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)
516 views37 pages

BCS 31

The document discusses (a) comparing structured and object-oriented programming, (b) inline functions and their advantages over normal functions, (c) passing objects as arguments to functions with an example, (d) the properties of friend functions, (e) the differences between constructors and automatic initialization and what copy constructors are, and (f) what function overloading is and how function calls are matched to overloaded functions with an example.

Uploaded by

Ls Payne
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

1. (a) Compare Structured programming with Object-oriented programming.

Give two advantages of


both.

Structured Programming Object-Oriented Programming

It relies on concept of objects that contain data


It is a subset of procedural programming. and code.

Programs are divided into small programs or


functions. Programs are divided into objects or entities.

It is all about facilitating creation of


programs with readable code and reusable It is all about creating objects that usually contain
components. both functions and data.

Its main aim is to improve and increase Its main aim is to improve and increase both
quality, clarity, and development time of quality and productivity of system analysis and
computer program. design.

It simply focuses on representing both structure


and behavior of information system into tiny or
It simply focuses on functions and processes small modules that generally combines data and
that usually work on data. process both.

It is a method of organizing, managing and


coding programs that can give or provide It is a method in which set of objects can vary
much easier modification and dynamically and can execute just by acting and
understanding. reading to each other.

In this, methods are written globally and


code lines are processed one by one i.e., In this, method works dynamically, make calls as
Run sequentially. per need of code for certain time.

It generally follows “Top-Down Approach”. It generally follows “Bottom-Up Approach”.

It provides less flexibility and abstraction as It provides more flexibility and abstraction as
compared to object-oriented programming. compared to structured programming.
It is more difficult to modify structured It is less difficult to modify object-oriented
program and reuse code as compared to programs and reuse code as compared to
object-oriented programs. structured programs.

It gives more importance of code. It gives more importance to data.

(b) What are Inline Functions ? How does the execution of inline functions differ from normal functions
? Give the advantages of inline functions. 5
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
complex tasks, the overhead of the function call is usually insignificant compared to the amount of
time the function takes to run. However, for small, commonly-used functions, the time needed to
make the function call is often a lot more than the time needed to actually execute the function’s
code. This overhead occurs for small functions because execution time of small function is less than
the switching time.
Inline functions provide following advantages:
1) Function call overhead doesn’t occur.
2) It also saves the overhead of push/pop variables on the stack when function is called.
3) It also saves overhead of a return call from a function.
4) When you inline a function, you may enable compiler to perform context specific optimization on
the body of function. Such optimizations are not possible for normal function calls. Other
optimizations can be obtained by considering the flows of calling context and the called context.
5) Inline function may be useful (if it is small) for embedded systems because inline can yield less code
than the function call preamble and return.

(c) Explain passing of objects as argument to a function with the help of an example. 5
Passing an Object as argument
To pass an object as an argument we write the object name as the argument while calling the function
the same way we do it for other variables.
Syntax: function_name(object_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’
function is called. In this method, we can pass objects as an argument and alter them. Although Java
is strictly passed by value, the precise effect differs between whether a primitive type or a reference
type is passed. When we pass a primitive type to a method, it is passed by value. But when we pass an
object to a method, the situation changes dramatically, because objects are passed by what is
effectively call-by-reference. Java does this interesting thing that’s sort of a hybrid between pass-by-
value and pass-by-reference. Basically, a parameter cannot be changed by the function, but the
function can ask the parameter to change itself via calling some method within it.
While creating a variable of a class type, we only create a reference to an object. Thus, when we pass
this reference to a method, the parameter that receives it will refer to the same object as that
referred to by the argument. This effectively means that objects act as if they are passed to methods
by use of call-by-reference. Changes to the object inside the method do reflect the object used as an
argument.

(d) What is a Friend Function ? Briefly discuss the properties of a friend function. 5
Characteristics of a Friend function:
The function is not in the scope of the class to which it has been declared as a friend.
It cannot be called using the object as it is not in the scope of that class.
It can be invoked like a normal function without using the object.
It cannot access the member names directly and has to use an object name and dot membership
operator with the member name.
It can be declared either in the private or the public part.
- A friend function is not in the scope of the class, in which it has been declared as friend.
- It cannot be called using the object of that class.
- It can be invoked like a normal function without any object.
- Unlike member functions, it cannot use the member names directly.
- It can be declared in public or private part without affecting its meaning.
- Usually, it has objects as arguments.

(e) How does Constructor differ from Automatic Initialization ? Briefly discuss the term Copy
Constructor. 5
A constructor is different from normal functions in following ways:
Constructor has same name as the class itself
Default Constructors don’t have input argument however, Copy and Parameterized Constructors have
input arguments Constructors don’t have return type
A constructor is automatically called when an object is created.
It must be placed in public section of class.
If we do not specify a constructor, C++ compiler generates a default constructor for object (expects no
parameters and has an empty body). types of constructors in C++ by taking a real-world example.
Suppose you went to a shop to buy a marker. When you want to buy a marker, what are the options.
The first one you go to a shop and say give me a marker. So just saying give me a marker mean that
you did not set which brand name and which color, you didn’t mention anything just say you want a
marker. So when we said just I want a marker so whatever the frequently sold marker is there in the
market or in his shop he will simply hand over that. And this is what a default constructor is! The
second method is you go to a shop and say I want a marker a red in color and XYZ brand. So you are
mentioning this and he will give you that marker. So in this case you have given the parameters. And
this is what a parameterized constructor is! Then the third one you go to a shop and say I want a
marker like this(a physical marker on your hand). So the shopkeeper will see that marker. Okay, and
he will give a new marker for you. Copy Constructor: A copy constructor is a member function that
initializes an object using another object of the same class. A detailed article on Copy Constructor.
Whenever we define one or more non-default constructors( with parameters ) for a class, a default
constructor( without parameters ) should also be explicitly defined as the compiler will not provide a
default constructor in this case. However, it is not necessary but it’s considered to be the best practice
to always define a default constructor. Copy constructor takes a reference to an object of the same
class as an argument.

(f) What is Function Overloading ? How are function calls matched with overloaded functions ? Explain
with the help of an example. 5

Function overloading is a feature of object-oriented programming where two or


more functions can have the same name but different parameters. 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
a polymorphism feature in C++.
#include <iostream>
using namespace std;
void add(int a, int b)
{ cout << "sum = " << (a + b);
}
void add(double a, double b)
{ cout << endl << "sum = " << (a + b);
}
// Driver code
int main()
{add(10, 2);
add(5.3, 6.2);
return 0;
}

Output
sum = 12
sum = 11.5

(g) Compare Early Binding and Late Binding. Explain when to use which type of binding. 5

Early Binding Late Binding

It is a compile-time process It is a run-time process


Early Binding Late Binding

The method definition and method call are linked The method definition and method call are
during the compile time. linked during the run time.

Actual object is not used for binding. Actual object is used for binding.

For example: Method overloading For example: Method overriding

Program execution is faster Program execution is slower

(h) What are Exceptions in C++ ? How is exception handling done in C++ ? Briefly discuss the functioning
of Try, Throw and Catch expressions with suitable block diagram. 5
One of the advantages of C++ over C is Exception Handling. Exceptions are runtime anomalies or
abnormal conditions that a program encounters during its execution. There are two types of
exceptions: a)Synchronous, b)Asynchronous (i.e., exceptions which are beyond the program’s control,
such as disc failure, keyboard interrupts etc.). C++ provides the following specialized keywords for this
purpose: try: Represents a block of code that can throw 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.
1) Separation of Error Handling code from Normal Code: In traditional error handling codes, there are
always if-else 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.
2) Functions/Methods can handle only the 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 the caller. If the caller chooses not to catch them, then the exceptions are
handled by the 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).
3) Grouping of Error Types: In C++, both basic types and objects can be thrown as exceptions. We can
create a hierarchy of exception objects, group exceptions in namespaces or classes and categorize
them according to their types.
C++ Exceptions: When executing C++ code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, C++ will normally stop and generate an error message. The technical term for
this is: C++ will throw an exception (error).
2. (a) Briefly discuss the term Message Passing. How does message passing support the concept of
interfaces in C++ ? 5
message passing is a technique for invoking behaviour (i.e., running a program) on a computer. The
invoking of a program sends a message to a process (which may be an actor or object) and relies on the
process and the supporting infrastructure to select and invoke the actual code to run. Message passing
differs from conventional programming where a process, subroutine, or function is directly invoked by
name. Messaging design patterns allow components and applications to exchange information. Through
separating component interaction from component functionality, it facilitates decoupling, encapsulation
and reusability. The motivation of introducing them is creating the intermediary layer that transfers the
message from sender to receiver. The sender and the recipient don’t need to think about how the
message is transferred, it is the responsibility of the messenger.
Messaging design pattern is used to implement or help implement other well-known design patterns
like Gang of Four design patterns.
One of the patterns that explain how the communication between objects could be implemented is the
Strategy pattern.
Strategy pattern The strategy pattern (also known as the rule pattern) is a pattern in behavioural
software design that enables an algorithm to be selected at runtime. Instead of implementing a single
algorithm directly, code receives run-time instructions to which in a family of algorithms to use.
The main point of this blog post is to show how Object A and Object B need to know about each other.
The algorithm will be chosen in run time.
With strategy pattern we can hide the details of algorithm implementation, so the use of a different
strategy will perform the same functionality of object differently.
The example will be written in C# code but if you are familiar with any other object-oriented language
you will not have a problem understanding the big idea.

(b) Differentiate between C and C++, give at least five differences.

C C++

C was developed by Dennis Ritchie between C++ was developed by Bjarne Stroustrup in
the year 1969 and 1973 at AT&T Bell Labs. 1979.

C does no support polymorphism,


encapsulation, and inheritance which means C++ supports polymorphism, encapsulation,
that C does not support object oriented and inheritance because it is an object oriented
programming. programming language.

C is a subset of C++. C++ is a superset of C.

C contains 32 keywords. C++ contains 63 keywords.


C C++

C++ is known as hybrid language because C++


For the development of code, C supports both procedural and object oriented
supports procedural programming. programming paradigms.

Data and functions are separated in C because Data and functions are encapsulated together in
it is a procedural programming language. form of an object in C++.

Data is hidden by the Encapsulation to ensure


that data structures and operators are used as
C does not support information hiding. intended.

Built-in & user-defined data types is supported


Built-in data types is supported in C. in C++.

C is a function driven language because C is a C++ is an object driven language because it is an


procedural programming language. object oriented programming.

Function and operator overloading is not Function and operator overloading is supported
supported in C. by C++.

C is a function-driven language. C++ is an object-driven language

Functions in C are not defined inside


structures. Functions can be used inside a structure in C++.

Namespace features are not present inside the Namespace is used by C++, which avoid name
C. collisions.

Header file used by C is stdio.h. Header file used by C++ is iostream.h.

Reference variables are not supported by C. Reference variables are supported by C++.

Virtual and friend functions are not supported Virtual and friend functions are supported by
by C. C++.
C C++

C does not support inheritance. C++ supports inheritance.

Instead of focusing on data, C focuses on C++ focuses on data instead of focusing on


method or process. method or procedure.

C provides malloc() and calloc() functions C++ provides new operator for memory
for dynamic memory allocation, and free() for allocation and delete operator for memory de-
memory de-allocation. allocation.

Direct support for exception handling is not


supported by C. Exception handling is supported by C++.

scanf() and printf() functions are used for


input/output in C. cin and cout are used for input/output in C++.

C structures don’t have access modifiers. C ++ structures have access modifiers.

C follows the top-down approach C++ follows the Bottom-up approach

Strict type checking in done in C++. So many


programs that run well in C compiler will result
There is no strict type checking in C in many warnings and errors under C++
programming language. compiler.

C does not support overloading C++ does support overloading

(c) What is Type Conversion ? What is the advantage of Type Conversion ? Briefly discuss Type Casting
and Automatic Type Conversion.
A type cast is basically a conversion from one type to another. There are two types of type conversion:
Implicit Type Conversion Also known as ‘automatic type conversion’.
Done by the compiler on its own, without any external trigger from the user.
Generally takes place when in an expression more than one data type is present. In such condition
type conversion (type promotion) takes place to avoid lose of data.
All the data types of the variables are upgraded to the data type of the variable with largest data type.
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double It is possible for implicit conversions to lose information,
signs can be lost (when signed is implicitly converted to unsigned), and overflow can occur (when long
long is implicitly converted to float). Explicit Type Conversion: This process is also called type casting
and it is user-defined. Here the user can typecast the result to make it of a particular data type.
In C++, it can be done by two ways:
Converting by assignment: This is done by explicitly defining the required type in front of the
expression in parenthesis. This can be also considered as forceful casting.
Syntax: (type) expression where type indicates the data type to which the final result is converted.
Conversion using Cast operator: A Cast operator is an unary operator which forces one data type to be
converted into another data type.
C++ supports four types of casting:
Static Cast
Dynamic Cast
Const Cast
Reinterpret Cast

(d) Compare Break and Continue statement. Exhibit the usage of break and continue statement with
suitable code in C++.

Break Statement Continue Statement

The Break statement is used to exit from the The continue statement is not used to exit
loop constructs. from the loop constructs.

The break statement is usually used with the The continue statement is not used with the
switch statement, and it can also use it within switch statement, but it can be used within the
the while loop, do-while loop, or the for-loop. while loop, do-while loop, or for-loop.

When a break statement is encountered then When the continue statement is encountered
the control is exited from the loop construct then the control automatically passed from
immediately. the beginning of the loop statement.

Syntax: Syntax:
break; continue;

3. (a) What is a Static Member Function ? Write a program in C++ to illustrate the concept of the static
member function.
class members static using static keyword. When we declare a member of a class as static it means no
matter how many objects of the class are created, there is only one copy of the static member.
A static member is shared by all objects of the class. All static data is initialized to zero when the first
object is created, if no other initialization is present. We can't put it in the class definition but it can be
initialized outside the class as done in the following example by redeclaring the static variable, using the
scope resolution operator :: to identify which class it belongs to.
Let us try the following example to understand the concept of static data members −
#include <iostream>
using namespace std;
class Box {
public:
static int objectCount;
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
}
double Volume() {
return length * breadth * height;
}

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

// Initialize static member of class Box


int Box::objectCount = 0;

int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
// Print total number of objects.
cout << "Total objects: " << Box::objectCount << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Constructor called.
Constructor called.
Total objects: 2
(b) What is a Destructor in C++ ? Discuss the naming conventions of destructor. Do constructors and
destructors have return type ? 5
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. Destructor is also a special member function like constructor. Destructor destroys
the class objects created by constructor. Destructor has the same name as their class name preceded
by a tiled (~) symbol. It is not possible to define more than one destructor.
The destructor is only one way to destroy the object create by constructor. Hence destructor can-not
be overloaded. Destructor neither requires any argument nor returns any value.
It is automatically called when object goes out of scope. Destructor release memory space occupied
by the objects created by constructor. In destructor, objects are destroyed in the reverse of an object
creation. 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. If we do not write our own destructor in class, compiler creates a
default destructor for us. The default destructor works fine unless we have dynamically allocated
memory or pointer in class. When a class contains a pointer to memory allocated in class, we should
write a destructor to release memory before the class instance is destroyed. This must be done to
avoid memory leak.

(c) What is Access Specifier ? Explain different access specifiers in C++. 5


Access modifiers are used to implement an important aspect of Object-Oriented Programming known
as Data Hiding. Consider a real-life example: Access Modifiers or Access Specifiers in a class are used
to assign the accessibility to the class members, i.e., they set some restrictions on the class members
so that they can’t be 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 of these access modifiers in detail:
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 from anywhere in the program using the
direct member access operator (.) with the object of that class.

(d) Explain the use of ‘&&’ and ‘!’ operators in C++ with the help of an example. 5
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 && b returns
true when both a and b are true (i.e. non-zero)(See this article for more reference).
(4 != 5) && (4 < 5); // true
Operators are the foundation of any programming language. We can define operators as symbols that
help us to perform specific mathematical and logical computations on operands. In other words, we
can say that an operator operates the operands. For example, ‘+’ is an operator used for addition, as
shown below: c = a + b;
Here, ‘+’ is the operator known as the addition operator and ‘a’ and ‘b’ are operands. The addition
operator tells the compiler to add both of the operands ‘a’ and ‘b’.

4. (a) What is Inheritance ? What are the advantages of inheritance ? Explain with the help of example. 5
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object-Oriented
Programming. Inheritance is a feature or a process in which, new classes are created from the
existing classes. The new class created is called “derived class” or “child class” and the existing class is
known as the “base class” or “parent class”. The derived class now is said to be inherited from the
base class.
When we say derived class inherits the base class, it means, the derived class inherits all the
properties of the base class, without changing the properties of base class and may add new features
to its own. These new features in the derived class will not affect the base class. The derived class is
the specialized class for the base class.
Sub Class: The class that inherits properties from another class is called Subclass or Derived Class.
Super Class: The class whose properties are inherited by a subclass is called Base Class or Superclass.
The article is divided into the following subtopics:
Why and when to use inheritance? Modes of Inheritance
Types of Inheritance 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 the same for all three classes. If we create these classes
avoiding inheritance then we have to write all of these functions in each of the three classes

(b) Compare Multi-level and Multiple inheritance in C++ with the help of an example. 5

Multiple Inheritance vs Multilevel Inheritance


Multiple Inheritance is an Inheritance Multilevel Inheritance is an Inheritance type that
type where a class inherits from more inherits from a derived class, making that derived
than one base class. class a base class for a new class.
Usage
Multiple Inheritance is not widely
used because it makes the system Multilevel Inheritance is widely used.
more complex.
Class Levels
Multiple Inheritance has two class Multilevel Inheritance has three class levels
levels namely, base class and derived namely, base class, intermediate class and derived
class. class.
(c) What are the limitations of Operator overloading and Function overloading. 5

Function overloading is one of the important features of object-oriented programming. It allows users
to have more than one function having the same name but different properties. Overloaded functions
enable users to supply different semantics for a function, depending on the signature of functions.
Advantages of function overloading are as follows:
The main advantage of function overloading is that it improves code readability and allows code
reusability. The use of function overloading is to save memory space, consistency, and readability.
It speeds up the execution of the program Code maintenance also becomes easy. Function
overloading brings flexibility to code. The function can perform different operations and hence it
eliminates the use of different function names for the same kind of operations.
Disadvantage of function overloading are as follows: Function declarations that differ only in the
return type cannot be overloaded It gives an error because the function cannot be overloaded by
return type only.
Member function declarations with the same name and the same parameter types cannot be
overloaded if any of them is a static member function declaration.
The main disadvantage is that it requires the compiler to perform name mangling on the function
name to include information about the argument types.

(d) Compare Compile-time Polymorphism with Run-time Polymorphism. 5

Compile Time Polymorphism Run time Polymorphism

In Compile time Polymorphism, the call is In Run time Polymorphism, the call is not
resolved by the compiler. resolved by the compiler.

It is also known as Static binding, Early binding It is also known as Dynamic binding, Late
and overloading as well. binding and overriding as well.

Method overloading is the compile-time Method overriding is the runtime


polymorphism where more than one methods polymorphism having the same method with
share the same name with different parameters same parameters or signature but associated
or signature and different return type. withcompared, different classes.

It is achieved by function overloading and It is achieved by virtual functions and


operator overloading. pointers.
Compile Time Polymorphism Run time Polymorphism

It provides fast execution because the method It provides slow execution as compare to
that needs to be executed is known early at the early binding because the method that needs
compile time. to be executed is known at the runtime.

Compile time polymorphism is less flexible as all Run time polymorphism is more flexible as all
things execute at compile time. things execute at run time.

Inheritance is not involved. Inheritance is involved.

5. (a) What are Stream Manipulators ? Briefly discuss the purpose of various stream manipulators. 5
Manipulators are helping functions that can modify the input/output stream. It does not mean that
we change the value of a variable, it only modifies the I/O stream using insertion (<<) and extraction
(>>) operators. Manipulators are special functions that can be included in the I/O statement to alter
the format parameters of a stream.
Manipulators are operators that are used to format the data display.
To access manipulators, the file iomanip.h should be included in the program.
For example, if we want to print the hexadecimal value of 100 then we can print it as:
cout<<setbase(16)<<100
Types of Manipulators There are various types of manipulators:
Manipulators without arguments: The most important manipulators defined by the IOStream
library are provided below. endl: It is defined in ostream. It is used to enter a new line and after
entering a new line it flushes (i.e. it forces all the output written on the screen or in the file) the
output stream.
ws: It is defined in istream and is used to ignore the whitespaces in the string sequence.
ends: It is also defined in ostream and it inserts a null character into the output stream. It typically
works with std::ostrstream, when the associated output buffer needs to be null-terminated to be
processed as a C string.
flush: It is also defined in ostream and it flushes the output stream, i.e. it forces all the output written
on the screen or in the file. Without flush, the output would be the same, but may not appear in real-
time.

(b) Compare Class templates and Function templates with the help of example code. 5
C++ Function Template Syntax
1 template<class type>ret-type func-name(parameter list)
2 {
3 //body of the function
4 }
Here, type is a placeholder name for a data type used by the function. It is used within the function
definition.
The class keyword is used to specify a generic type in a template declaration.
C++ function template example:
Source Code:
#include<iostream.h>
using namespace std;
template<classX>//can replace 'class" keyword by "typename" keyword
X func( Xa,Xb)
{
return a;
}
int main()
count<<func(15,8),,endl;//func(int,int);
count,,func('p','q'),,endl;//func(char,char);
count<<func(7.5,9.2),,endl;//func(double,double)
return();
}
Output:
15
p
7.5
The class template in c++ is like function templates. They are known as generic templates. They
define a family of classes in C++.
Syntax of Class Template
1 template<class Ttype>
2 class class_name
3 {
4 //class body;
5 }
Here Ttype is a placeholder type name, which will be specified when a class instantiated.
The Ttype can be used inside the body of the class.

(i) Default and Parameterized Constructor


Default Constructor A default constructor is a 0 argument constructor which contains a no-argument call
to the super class constructor. To assign default values to the newly created objects is the main
responsibility of default constructor.
Compiler writes a default constructor in the code only if the program does not write any constructor in
the class.
The access modifier of default constructor is always the same as a class modifier but this rule is
applicable only for “public” and “default” modifiers.
Parameterized Constructors
The parameterized constructors are the constructors having a specific number of arguments to be
passed.
The purpose of a parameterized constructor is to assign user-wanted specific values to the instance
variables of different objects.
A parameterized constructor is written explicitly by a programmer.
The access modifier of default constructor is always the same as a class modifier but this rule is
applicable only for “public” and “default” modifiers.

(ii) Virtual Functions and their limitations


A virtual function is a member function which is declared within a base class and is re-defined
(overridden) by a derived class. When you refer to a derived class object using a pointer or a reference
to the base class, you can call a virtual function for that object and execute the derived class’s version
of the function.
Virtual functions ensure that the correct function is called for an object, regardless of the type of
reference (or pointer) used for function call.
They are mainly used to achieve Runtime polymorphism
Functions are declared with a virtual keyword in base class.
The resolving of function call is done at runtime.

1. (a) Explain, how structured programming paradigm is different from object oriented
paradigm.

Structured Programming Object-Oriented Programming

It relies on concept of objects that contain data


It is a subset of procedural programming. and code.

Programs are divided into small programs or


functions. Programs are divided into objects or entities.

It is all about facilitating creation of


programs with readable code and reusable It is all about creating objects that usually contain
components. both functions and data.

Its main aim is to improve and increase Its main aim is to improve and increase both
quality, clarity, and development time of quality and productivity of system analysis and
computer program. design.

It simply focuses on representing both structure


and behavior of information system into tiny or
It simply focuses on functions and processes small modules that generally combines data and
that usually work on data. process both.
It is a method of organizing, managing and
coding programs that can give or provide It is a method in which set of objects can vary
much easier modification and dynamically and can execute just by acting and
understanding. reading to each other.

In this, methods are written globally and


code lines are processed one by one i.e., In this, method works dynamically, make calls as
Run sequentially. per need of code for certain time.

It generally follows “Top-Down Approach”. It generally follows “Bottom-Up Approach”.

It provides less flexibility and abstraction as It provides more flexibility and abstraction as
compared to object-oriented programming. compared to structured programming.

It is more difficult to modify structured It is less difficult to modify object-oriented


program and reuse code as compared to programs and reuse code as compared to
object-oriented programs. structured programs.

It gives more importance of code. It gives more importance to data.

(b) What is encapsulation ? How is it different from information hiding ? Explain with the help of an
example.
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds
together code and the data it manipulates. Another way to think about encapsulation is, that it is a
protective shield that prevents the data from being accessed by the code outside this shield.
Technically in encapsulation, the variables or data of a class is hidden from any other class and can be
accessed only through any member function of its own class in which it is declared.
As in encapsulation, the data in a class is hidden from other classes using the data hiding concept
which is achieved by making the members or methods of a class private, and the class is exposed to
the end-user or the world without providing any details behind implementation using the abstraction
concept, so it is also known as a combination of data-hiding and abstraction.
Encapsulation can be achieved by Declaring all the variables in the class as private and writing public
methods in the class to set and get the values of variables.
It is more defined with the setter and getter method.
Advantages of Encapsulation:
Data Hiding: it is a way of restricting the access of our data members by hiding the implementation
details. Encapsulation also provides a way for data hiding. The user will have no idea about the inner
implementation of the class. It will not be visible to the user how the class is storing values in the
variables. The user will only know that we are passing the values to a setter method and variables are
getting initialized with that value.
Increased Flexibility: We can make the variables of the class read-only or write-only depending on our
requirement. If we wish to make the variables read-only then we have to omit the setter methods like
setName(), setAge(), etc. from the above program or if we wish to make the variables write-only then
we have to omit the get methods like getName(), getAge(), etc. from the above program
Reusability: Encapsulation also improves the re-usability and is easy to change with new
requirements.
Testing code is easy: Encapsulated code is easy to test for unit testing.

(c) Explain the concept of copy constructor with the help of an example and program.5
A copy constructor is a member function that initializes an object using another object of the same
class. A copy constructor has the following general function prototype:
ClassName (const ClassName &old_obj);
Copy constructor is used to initialize the members of a newly created object by copying the members
of an already existing object.
Copy constructor takes a reference to an object of the same class as an argument.
Sample(Sample &t)
{
id=t.id;
}
The process of initializing members of an object through a copy constructor is known as copy
initialization.
It is also called member-wise initialization because the copy constructor initializes one object with the
existing object, both belonging to the same class on a member by member copy basis.
The copy constructor can be defined explicitly by the programmer. If the programmer does not define
the copy constructor, the compiler does it for us.

(d) What is access control specifier ? Explain public access control specifier with
example.
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 into 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 the 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 the information (that is not
entitled to them) without having either assigned privileges (such as those possessed by a friend class
or an inherited class, as will be seen in this article ahead) or access to one of these 10 members 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, i.e., they set some restrictions on the class members so that they can’t be directly accessed
by the outside functions.
(e) Explain, how memory management is performed in C++. 5
C++ allows us to allocate the memory of a variable or an array in run time. This is known as dynamic
memory allocation.
In other programming languages such as Java and Python, the compiler automatically manages the
memories allocated to variables. But this is not the case in C++.
In C++, we need to deallocate the dynamically allocated memory manually after we have no use for the
variable.
We can allocate and then deallocate memory dynamically using the new and delete operators
respectively.
Memory management in C++ is a technique of managing the computer memory and assigning required
memory space to the programs for execution. It is almost relatable and is based on the same concept as
other Programming languages. It deals with the space and memory assignment in terms of
improvisation for the entire computer system and its performance. Arrays play a very vital role in
memory management as it helps in storing the data with appropriate spacing alignment, maintaining
the timing constraints, and thereby doing efficient resource management by allocating memory using
the new keyword

(f) What is a stream manipulator ? Explain the use of setw( ) and setprecision( ) as stream manipulator. 6
Manipulators are helping functions that can modify the input/output stream. It does not mean that
we change the value of a variable, it only modifies the I/O stream using insertion (<<) and extraction
(>>) operators.
Manipulators are special functions that can be included in the I/O statement to alter the format
parameters of a stream.
Manipulators are operators that are used to format the data display.
To access manipulators, the file iomanip.h should be included in the program.
Types of Manipulators There are various types of manipulators:
Manipulators without arguments: The most important manipulators defined by the IOStream
library are provided below.
endl: It is defined in ostream. It is used to enter a new line and after entering a new line it flushes (i.e.
it forces all the output written on the screen or in the file) the output stream.
ws: It is defined in istream and is used to ignore the whitespaces in the string sequence.
ends: It is also defined in ostream and it inserts a null character into the output stream. It typically
works with std::ostrstream, when the associated output buffer needs to be null-terminated to be
processed as a C string.
flush: It is also defined in ostream and it flushes the output stream, i.e. it forces all the output written
on the screen or in the file. Without flush, the output would be the same, but may not appear in real-
time.

(g) What is operator overloading ? Briefly discuss the general rules of operator overloading.
In C++, following are the general rules for operator overloading.
1) Only built-in operators can be overloaded. New operators can not be created.
2) Arity of the operators cannot be changed.
3) Precedence and associativity of the operators cannot be changed.
4) Overloaded operators cannot have default arguments except the function call operator () which can
have default arguments.
5) Operators cannot be overloaded for built in types only. At least one operand must be used defined
type.
6) Assignment (=), subscript ([]), function call (“()”), and member selection (->) operators must be
defined as member functions
7) Except the operators specified in point 6, all other operators can be either member functions or a
non member functions.
8 ) Some operators like (assignment)=, (address)& and comma (,) are by default overloaded.
Please write comments if you find anything incorrect, or you want to share more information about
the topic discussed above.

(h) What is scope resolution operator ? Explain its use with the help of a C++ program. 4
In C++, scope resolution operator is ::. It is used for following purposes.
1) To access a global variable when there is a local variable with same name:

// C++ program to show that we can access a global variable


// using scope resolution operator :: when there is a local
// variable with same name
#include<iostream>
using namespace std;
int x; // Global x
int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
return 0;
}

Output:
Value of global x is 0
Value of local x is 10

2) To define a function outside a class.

// C++ program to show that scope resolution operator :: is used


// to define a function outside a class
#include<iostream>
using namespace std;

class A
{
public:

// Only declaration
void fun();
};

// Definition outside class using ::


void A::fun()
{
cout << "fun() called";
}

int main()
{
A a;
a.fun();
return 0;
}

Output:
fun() called

2. (a) What is a container in C++ ? List main types of container in C++. Also list some common member
functions of Container class. 10
A container is a holder object that stores a collection of other objects (its elements). They are
implemented as class templates, which allows great flexibility in the types supported as elements.
The container manages the storage space for its elements and provides member functions to access
them, either directly or through iterators (reference objects with similar properties to pointers).
Sequence containers
Sequence containers implement data structures that can be accessed sequentially.
array: Static contiguous array (class template)
vector: Dynamic contiguous array (class template)
deque: Double-ended queue (class template)
forward_list: Singly-linked list (class template)
list: Doubly-linked list (class template)
Associative containers
Associative containers implement sorted data structures that can be quickly searched (O(log n)
complexity).
Set: Collection of unique keys, sorted by keys
(class template)
Map: Collection of key-value pairs, sorted by keys, keys are unique (class template).
multiset: Collection of keys, sorted by keys (class template)
multimap: Collection of key-value pairs, sorted by keys
(class template)
Unordered associative containers
Unordered associative containers implement unsorted (hashed) data structures that can be quickly
searched (O(1) amortized, O(n) worst-case complexity).
unordered_set: Collection of unique keys, hashed by keys. (class template)
unordered_map: Collection of key-value pairs, hashed by keys, keys are unique. (class template)
unordered_multiset: Collection of keys, hashed by keys (class template)
unordered_multimap: Collection of key-value pairs, hashed by keys (class template)
Container adaptors
Container adaptors provide a different interface for sequential containers.
stack: Adapts a container to provide stack (LIFO data structure) (class template).
queue: Adapts a container to provide queue (FIFO data structure) (class template).
priority_queue: Adapts a container to provide priority queue (class template).

(b) What is static member in C++ ? Explain the use of static data member and static member function
with the help of an example and program in C++. 10
Static data members are class members that are declared using static keywords. A static member has
certain special characteristics. These are:
Only one copy of that member is created for the entire class and is shared by all the objects of that
class, no matter how many objects are created.
It is initialized before any object of this class is being created, even before main starts.
It is visible only within the class, but its lifetime is the entire program
Syntax
static data_type data_member_name;
It is a variable which is declared with the static keyword, it is also known as class member, thus only
single copy of the variable creates for all objects.
Any changes in the static data member through one member function will reflect in all other object’s
member functions.
Declaration
static data_type member_name;
Defining the static data member
It should be defined outside of the class following this syntax:
data_type class_name :: member_name =value;
If you are calling a static data member within a member function, member function should be declared
as static (i.e. a static member function can access the static data members)
A static data member can also be accessed through the class name without using the static member
function (as it is a class member), here we need an Scope Resolution Operator (SRO) :: to access the
static data member without static member function.
Syntax:
class_name :: static_data_member;
(a) What do you mean by polymorphism ? How is runtime polymorphism different from compile time
polymorphism ? Give example(s) to support the above difference.

The word polymorphism means having many forms. In simple words, we can define polymorphism as
the ability of a message to be displayed in more than one form. In this article, we will see the
difference between two types of polymorphisms, compile time and run time.

Compile Time Polymorphism Run time Polymorphism

In Compile time Polymorphism, the call is In Run time Polymorphism, the call is not
resolved by the compiler. resolved by the compiler.

It is also known as Static binding, Early binding It is also known as Dynamic binding, Late
and overloading as well. binding and overriding as well.

Method overloading is the compile-time Method overriding is the runtime


polymorphism where more than one methods polymorphism having the same method with
share the same name with different parameters same parameters or signature but associated
or signature and different return type. withcompared, different classes.

It is achieved by function overloading and It is achieved by virtual functions and


operator overloading. pointers.

It provides fast execution because the method It provides slow execution as compare to
that needs to be executed is known early at the early binding because the method that needs
compile time. to be executed is known at the runtime.

Compile time polymorphism is less flexible as all Run time polymorphism is more flexible as all
things execute at compile time. things execute at run time.

(b) What is a virtual function ? How virtual function relates to inheritance ? What happens if we don't
use the virtual function in the inheritance ? Explain with the help of an example and program. 10

A virtual function is a member function which is declared within a base class and is re-defined
(overridden) by a derived class. When you refer to a derived class object using a pointer or a reference
to the base class, you can call a virtual function for that object and execute the derived class’s version
of the function.
Virtual functions ensure that the correct function is called for an object, regardless of the type of
reference (or pointer) used for function call.
They are mainly used to achieve Runtime polymorphism
Functions are declared with a virtual keyword in base class.
The resolving of function call is done at runtime.
Rules for Virtual Functions
Virtual functions cannot be static.
A virtual function can be a friend function of another class.
Virtual functions should be accessed using pointer or reference of base class type to achieve runtime
polymorphism.
The prototype of virtual functions should be the same in the base as well as derived class.
They are always defined in the base class and overridden in a derived class. It is not mandatory for the
derived class to override (or re-define the virtual function), in that case, the base class version of the
function is used.
A class may have virtual destructor but it cannot have a virtual constructor.
Compile time (early binding) VS runtime (late binding) behavior of Virtual Functions
Explanation: Runtime polymorphism is achieved only through a pointer (or reference) of base class
type. Also, a base class pointer can point to the objects of base class as well as to the objects of
derived class. In above code, base class pointer ‘bptr’ contains the address of object ‘d’ of derived
class.
Late binding (Runtime) is done in accordance with the content of pointer (i.e. location pointed to by
pointer) and Early binding (Compile time) is done according to the type of pointer, since print()
function is declared with virtual keyword so it will be bound at runtime (output is print derived
class as pointer is pointing to object of derived class) and show() is non-virtual so it will be bound
during compile time (output is show base class as pointer is of base type).

1. (a) Why are object oriented programming languages more popular than structured programming
languages ? Differentiate between structured and object oriented programming languages.

Structured Programming Object-Oriented Programming

It relies on concept of objects that contain data


It is a subset of procedural programming. and code.

Programs are divided into small programs or


functions. Programs are divided into objects or entities.

It is all about facilitating creation of


programs with readable code and reusable It is all about creating objects that usually contain
components. both functions and data.

Its main aim is to improve and increase Its main aim is to improve and increase both
quality, clarity, and development time of quality and productivity of system analysis and
computer program. design.
It simply focuses on representing both structure
and behavior of information system into tiny or
It simply focuses on functions and processes small modules that generally combines data and
that usually work on data. process both.

It is a method of organizing, managing and


coding programs that can give or provide It is a method in which set of objects can vary
much easier modification and dynamically and can execute just by acting and
understanding. reading to each other.

In this, methods are written globally and


code lines are processed one by one i.e., In this, method works dynamically, make calls as
Run sequentially. per need of code for certain time.

It generally follows “Top-Down Approach”. It generally follows “Bottom-Up Approach”.

It provides less flexibility and abstraction as It provides more flexibility and abstraction as
compared to object-oriented programming. compared to structured programming.

It is more difficult to modify structured It is less difficult to modify object-oriented


program and reuse code as compared to programs and reuse code as compared to
object-oriented programs. structured programs.

It gives more importance of code. It gives more importance to data.

(b) Explain ambiguity resolution in multiple inheritance. What happens if we don't use a virtual function
in the inheritance ?
In multiple inheritances, when one class is derived from two or more base classes then there may be a
possibility that the base classes have functions with the same name, and the derived class may not
have functions with that name as those of its base classes. If the derived class object needs to access
one of the similarly named member functions of the base classes then it results in ambiguity because
the compiler gets confused about which base’s class member function should be called.
Code Snippet:
We have created an “A” class which consists of the public member function “func”.
We have created a “B” class which also consists of the public member function “func”.
We have created a “C” class that is inheriting “A” and “B” classes.
Object “obj” is created of the derived class “C”.
The function “func” is called by the object “obj”.
The important thing to note here is that when the function “func” is called by the object “obj” first
time it will invoke the function “func” of the “A” class and when the function “func” is called by the
object “obj” second time it will invoke the function “func” of the “B” class because we had specified it
using scope resolution operator “::” to get rid of ambiguity.

(d) Define the Standard Template Library. How is the class template different from the function
template ? Explain. 6
The Standard Template Library (STL) is a set of C++ template classes to provide common programming
data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes,
algorithms, and iterators. It is a generalized library and so, its components are parameterized.
Working knowledge of template classes is a prerequisite for working with STL.
Algorithms
Containers
Functions
Iterators
Algorithms
The header algorithm defines a collection of functions specially designed to be used on a range of
elements. They act on containers and provide means for various operations for the contents of the
containers.
Algorithm
Sorting
Searching
Important STL Algorithms
Useful Array algorithms
Partition Operations
Numeric
valarray class
Containers
Containers or container classes store objects and data. There are in total seven standards “first-class”
container classes and three container adaptor classes and only seven header files that provide access
to these containers or container adaptors.
Sequence Containers: implement data structures that can be accessed in a sequential manner.
vector
list
deque
arrays
forward_list( Introduced in C++11)
Container Adaptors: provide a different interface for sequential containers.
queue
priority_queue
stack
Associative Containers: implement sorted data structures that can be quickly searched (O(log n)
complexity).
set
multiset
map
multimap
Unordered Associative Containers: implement unordered data structures that can be quickly searched
unordered_set (Introduced in C++11)
unordered_multiset (Introduced in C++11)
unordered_map (Introduced in C++11)
unordered_multimap (Introduced in C++11)

(e) Differentiate between private, protected and public access modifiers with the help of an example for
each. 6

Public Access Private Access Protected access Package access


Modifier Modifier modifier modifier

This modifier is
applicable for This modifier is not This modifier is not This modifier is
both top-level applicable for both applicable for both top- applicable for both top-
classes and top-level classes level classes and level classes and
interfaces. and interfaces. interfaces. interfaces.

Public members Private members


can be accessed cannot be Package members can
from the child accessed from the Protected members can be be accessed from the
class of the same child class of the accessed from the child child class of the same
package. same package. class of the same package. package.

Private members
Public member cannot be
can be accessed accessed from Protected member can be Package member can
from non-child non-child classes accessed from non-child be accessed from non-
classes of the of the same classes of the same child class of the same
same package. package. package. package.

Public members Private members Protected members can be


can be accessed cannot be accessed from the child Package members
from the child accessed from the class of the outside cannot be accessed
class of outside child class of package, but we should from the child class of
package. outside package. use child reference only. outside package.

Public members Private members


can be accessed cannot be Protected members Package members
from non-child accessed from cannot be accessed from cannot be accessed
Public Access Private Access Protected access Package access
Modifier Modifier modifier modifier

class of outside non-child class of the non-child class of from non-child class of
package. outside package. outside package. outside package.

Protected modifier is more Package modifier is


Public modifier is accessible than the more restricted than
the most Private modifier is package and private the public and
accessible the most restricted modifier but less protected modifier but
modifier among modifier among all accessible than public less restricted than the
all modifiers. modifiers. modifier. private modifier.

(f) How is constructor different from the `constructor with argument' ? Explain by using an example. 6
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 why it is known as constructors.
Constructor does not have a return value, hence they do not have a return type.
A constructor is different from normal functions in following ways:
Constructor has same name as the class itself
Default Constructors don’t have input argument however, Copy and Parameterized Constructors have
input arguments
Constructors don’t have return type
A constructor is automatically called when an object is created.
It must be placed in public section of class.
If we do not specify a constructor, C++ compiler generates a default constructor for object (expects no
parameters and has an empty body).
Characteristics of the constructor:
The name of the constructor is the same as its class name.
Constructors are mostly declared in the public section of the class though it can be declared in the
private section of the class.
Constructors do not return values; hence they do not have a return type.
A constructor gets called automatically when we create the object of the class.
Constructors can be overloaded.
Constructor can not be declared virtual.

(a) Write a program to demonstrate the catching of all exceptions. What happens when a raised
exception is not caught by catch-block (in the absence of catching all exception blocks) ? 10
One of the advantages of C++ over C is Exception Handling. Exceptions are runtime anomalies or
abnormal conditions that a program encounters during its execution. There are two types of
exceptions: a)Synchronous, b)Asynchronous (i.e., exceptions which are beyond the program’s control,
such as disc failure, keyboard interrupts etc.). C++ provides the following specialized keywords for this
purpose: try: Represents a block of code that can throw 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.
Why Exception Handling?
The following are the main advantages of exception handling over traditional error handling
1) Separation of Error Handling code from Normal Code: In traditional error handling codes, there are
always if-else 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.
2) Functions/Methods can handle only the 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 the caller. If the caller chooses not to catch them, then the exceptions are
handled by the 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).
3) Grouping of Error Types: In C++, both basic types and objects can be thrown as exceptions. We can
create a hierarchy of exception objects, group exceptions in namespaces or classes and categorize
them according to their types.

(b) Write a program to implement the overloading of « operator. 10


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.
Example:
int a;
float b,sum;
sum=a+b;
Here, variables “a” and “b” are of types “int” and “float”, which are built-in data types. Hence the
addition operator ‘+’ can easily add the contents of “a” and “b”. This is because the addition operator
“+” is predefined to add variables of built-in data type only.
Now, consider another example
class A
{
};
int main()
{
A a1,a2,a3;
a3= a1 + a2;
return 0;
}
In this example, we have 3 variables “a1”, “a2” and “a3” of type “class A”. Here we are trying to add
two objects “a1” and “a2”, which are of user-defined type i.e. of type “class A” using the “+” operator.
This is not allowed, because the addition operator “+” is predefined to operate only on built-in data
types. But here, “class A” is a user-defined type, so the compiler generates an error. This is where the
concept of “Operator overloading” comes in.
Now, if the user wants to make the operator “+” to add two class objects, the user has to redefine the
meaning of the “+” operator such that it adds two class objects. This is done by using the concept
“Operator overloading”. So the main idea behind “Operator overloading” is to use c++ operators with
class variables or class objects. Redefining the meaning of operators really does not change their
original meaning; instead, they have been given additional meaning along with their existing ones.

(a) How do we declare static class data ? Explain the syntax and rules to define static class data
Static data members are class members that are declared using static keywords. A static member has
certain special characteristics. These are:
Only one copy of that member is created for the entire class and is shared by all the objects of that
class, no matter how many objects are created.
It is initialized before any object of this class is being created, even before main starts.
It is visible only within the class, but its lifetime is the entire program
Syntax
static data_type data_member_name;
C++

#include <iostream>
using namespace std;

class A
{
public:
A() { cout << "A's Constructor Called " << endl; }
};

class B
{
static A a;
public:
B() { cout << "B's Constructor Called " << endl; }
};

int main()
{
B b;
return 0;
}

Output:
B's Constructor Called
The above program calls only B’s constructor, it doesn’t call A’s constructor. The reason for this is
simple, static members are only declared in a class declaration, not defined. They must be explicitly
defined outside the class using the scope resolution operator.
If we try to access static member ‘a’ without an explicit definition of it, we will get a compilation error.
For example, the following program fails in the compilation.

(b) Write a short program to implement the concept of passing object as argument. 5
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 the argument while calling the function
the same way we do it for other variables.
Syntax:
function_name(object_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’
function is called. In this method, we can pass objects as an argument and alter them.
CPP

// 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;
}
};

// 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);

// 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

New values
Value of object 1: 50
& object 2: 150

(a) What is the importance of Abstract Class ? Write a program to implement the concept of abstract
class in C++. Also explain why an abstract class cannot be instantiated. 10
Sometimes implementation of all function cannot be provided in a base class because we don’t know
the implementation. Such a class is called abstract class. For example, let Shape be a base class. We
cannot provide implementation of function draw() in Shape, but we know every derived class must
have implementation of draw(). Similarly an Animal class doesn’t have implementation of move()
(assuming that all animals move), but all animals must know how to move. We cannot create objects
of abstract classes.A pure virtual function (or abstract function) in C++ is a virtual function for which
we can have implementation, But we must override that function in the derived class, otherwise the
derived class will also become abstract class (For more info about where we provide implementation
for such functions refer to this https://stackoverflow.com/questions/2089083/pure-virtual-function-
with-implementation). A pure virtual function is declared by assigning 0 in declaration. See the
following example.
CPP

// An abstract class
class Test
{
// Data members of class
public:
// Pure Virtual Function
virtual void show() = 0;

/* Other members */
};

A complete example:
A pure virtual function is implemented by classes which are derived from a Abstract class. Following is
a simple example to demonstrate the same.
CPP

#include<iostream>
using namespace std;

class Base
{
int x;
public:
virtual void fun() = 0;
int getX() { return x; }
};

// This class inherits from Base and implements fun()


class Derived: public Base
{
int y;
public:
void fun() { cout << "fun() called"; }
};
int main(void)
{
Derived d;
d.fun();
return 0;
}

Output:
fun() called

5. Write short notes on the following : 4 x 5=20


(a) Destructor 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.
Destructor is also a special member function like constructor. Destructor destroys the class objects
created by constructor.
Destructor has the same name as their class name preceded by a tiled (~) symbol.
It is not possible to define more than one destructor.
The destructor is only one way to destroy the object create by constructor. Hence destructor can-not
be overloaded.
Destructor neither requires any argument nor returns any value.
It is automatically called when object goes out of scope.
Destructor release memory space occupied by the objects created by constructor.
In destructor, objects are destroyed in the reverse of an object creation.
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.

(b) Pure Virtual Function Sometimes implementation of all function cannot be provided in a base class
because we don’t know the implementation. Such a class is called abstract class. For example, let
Shape be a base class. We cannot provide implementation of function draw() in Shape, but we know
every derived class must have implementation of draw(). Similarly an Animal class doesn’t have
implementation of move() (assuming that all animals move), but all animals must know how to move.
We cannot create objects of abstract classes.
A pure virtual function (or abstract function) in C++ is a virtual function for which we can have
implementation, But we must override that function in the derived class, otherwise the derived class
will also become abstract class

(b) What is the need of memory management in C++ ? Explain the process of memory management in
C++. 5
arrays store the homogeneous data, so most of the time, memory is allocated to the array at the
declaration time. Sometimes the situation arises when the exact memory is not determined until
runtime. To avoid such a situation, we declare an array with a maximum size, but some memory will be
unused. To avoid the wastage of memory, we use the new operator to allocate the memory dynamically
at the run time.
Memory Management Operators In C language, we use the malloc() or calloc() functions to allocate the
memory dynamically at run time, and free() function is used to deallocate the dynamically allocated
memory. C++ also supports these functions, but C++ also defines unary operators such
as new and delete to perform the same tasks, i.e., allocating and freeing the memory.
New operator
A new operator is used to create the object while a delete operator is used to delete the object. When
the object is created by using the new operator, then the object will exist until we explicitly use the
delete operator to delete the object. Therefore, we can say that the lifetime of the object is not related
to the block structure of the program.
Syntax pointer_variable = new data-type
The above syntax is used to create the object using the new operator. In the above
syntax, 'pointer_variable' is the name of the pointer variable, 'new' is the operator, and 'data-
type' defines the type of the data.
Example 1:
int *p;
p = new int;
In the above example, 'p' is a pointer of type int.

(g) What is scope resolution operator ? Explain the use of scope resolution operator with the help of a
C++ program. 5
In C++, scope resolution operator is ::. It is used for following purposes.
1) To access a global variable when there is a local variable with same name:

// C++ program to show that we can access a global variable


// using scope resolution operator :: when there is a local
// variable with same name
#include<iostream>
using namespace std;

int x; // Global x

int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
return 0;
}

Output:
Value of global x is 0
Value of local x is 10
(h) Explain any five relational operators in C++ with the help of examples. 5
A relational operator is used to check the relationship between two operands. For example,
// checks if a is greater than b
a > b;
Here, > is a relational operator. It checks if a is greater than b or not.
If the relation is true, it returns 1 whereas if the relation is false, it returns 0.
The following table summarizes the relational operators used in C++.

Operator Meaning Example

== Is Equal To 3 == 5 gives us false

!= Not Equal To 3 != 5 gives us true

> Greater Than 3 > 5 gives us false

< Less Than 3 < 5 gives us true

>= Greater Than or Equal To 3 >= 5 give us false

<= Less Than or Equal To 3 <= 5 gives us true

(c) What is function template ? Explain this concept, with the help of an example. 5
A template is a simple 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 to sort() for different data types. Rather than writing and maintaining
multiple codes, we can write one sort() and pass data type as a parameter.
C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The second keyword
can always be replaced by the keyword ‘class’.
How Do Templates Work? Templates are expanded at compiler time. This is like macros. The
difference is, that the compiler does type checking before template expansion. The idea is simple,
source code contains only function/class, but compiled code may contain multiple copies of the same
function/class.

5. Write short notes on the following (give example code in C++ for each) : 5 each
(a) Overriding concept in C++ The derived classes inherit features of the base class.
Suppose, the same function is defined in both the derived class and the based class. Now if we call this
function using the object of the derived class, the function of the derived class is executed.
This is known as function overriding in C++. The function in derived class overrides the function in base
class.
(b) Message passing - It is a form of communication used in object-oriented programming as well as
parallel programming. Message passing in Java is like sending an object i.e. message from one thread
to another thread. It is used when threads do not have shared memory and are unable to share
monitors or semaphores or any other shared variables to communicate. Suppose we consider an
example of producer and consumer, likewise what producer will produce, the consumer will be able
to consume that only.

(c) Encapsulation - Encapsulation is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates. Another way to think about
encapsulation is, that it is a protective shield that prevents the data from being accessed by the code
outside this shield.
Technically in encapsulation, the variables or data of a class is hidden from any other class and can be
accessed only through any member function of its own class in which it is declared.

(d) Object initialization and its need - Objects can be initialized using new Object(), Object.create(), or
using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or
more pairs of property names and associated values of an object, enclosed in curly braces ({}).

Common questions

Powered by AI

Structured programming relies on a subset of procedural programming where programs are divided into smaller functions, following a 'Top-Down Approach.' It emphasizes code readability and function reuse, but offers less flexibility and abstraction compared to object-oriented programming . Advantages include easier modification and understanding of code. On the other hand, object-oriented programming divides programs into objects that encapsulate data and behavior, following a 'Bottom-Up Approach' . It emphasizes flexibility and abstraction, facilitating easier code modification and reuse. Object-oriented programs also prioritize data over code .

Multiple inheritance in C++ can cause ambiguity when a derived class inherits from multiple base classes containing methods or members with the same name. This leads to confusion about which base class's method should be called . The solution is to use the scope resolution operator to explicitly specify which base class's member to use, thereby resolving the ambiguity . This explicit reference ensures the desired function or member from the appropriate base class is accessed.

Exception handling in C++ is a mechanism to manage runtime anomalies using the keywords 'try', 'throw', and 'catch' . A 'try' block contains code that may throw exceptions. If an exception occurs, it is thrown using the 'throw' keyword, which transfers control to a corresponding 'catch' block, designed to handle that specific exception . This separates error handling from regular code, promoting clearer and more maintainable code structures. 'try', 'throw', and 'catch' provide a robust framework to manage exceptions in a structured manner.

The Standard Template Library (STL) in C++ is a collection of template classes to provide generic data structures and algorithms such as lists, stacks, and arrays, facilitating code reuse and efficiency . Class templates allow customizable classes with generic definitions usable across different data types, whereas function templates enable functions to operate with generic types while maintaining the ability to handle various data types accordingly. While both templates parameterize operations over types, class templates provide broader structure, while function templates focus on achieving polymorphism in specific operations .

Inline functions eliminate the overhead associated with normal function calls by substituting the function code directly into the calling program at compile time. This is beneficial when the time needed to make a function call is more significant than the time required to execute the function's code itself, which is often the case for small functions . Advantages of inline functions include reduced function call overhead and potentially increased program efficiency .

Access specifiers in C++ define the accessibility of class members, directly supporting data hiding by restricting unauthorized access. The primary specifiers are 'public', 'private', and 'protected'. 'Public' members are accessible anywhere in the program, 'private' members are only accessible within the defining class, and 'protected' members are accessible within the class and its derived classes . By limiting access, these specifiers enforce encapsulation and safeguard the internal state of objects, adhering to the principles of information hiding and promoting encapsulation .

Encapsulation in C++ involves wrapping data and methods that operate on the data within a single unit or class, and it is implemented by making class members private and accessible only through public methods . Information hiding, a concept within encapsulation, restricts direct access to some of an object's components, exposing only necessary parts of the object through controlled interfaces. While encapsulation involves defining the object with both data and behavior, information hiding specifically focuses on limiting access to the object's internal state .

Function overloading in C++ allows multiple functions to have the same name but different parameters, which differentiates which function to execute. This feature supports polymorphism, a core aspect of object-oriented programming . For example, if two functions named 'add' are overloaded to handle integers or doubles, the compiler selects the correct version based on input type, like so: `void add(int a, int b); void add(double a, double b);` In the code, calling `add(10, 2);` invokes the integer version, while `add(5.3, 6.2);` invokes the double version .

Operator overloading in C++ allows developers to redefine the behavior of existing operators for user-defined types, enabling operators to work with class objects just as they do with built-in data types . For example, if a class defines a '+' operator, it can be used to add two class instances, expanding its functionality. This involves defining a special function to handle the operator for specific types, thereby providing intuitive and expressive operations tailored to the needs of custom types while preserving the original semantic integrity of the operators .

Early binding occurs at compile time, where the method definitions and calls are linked, leading to faster program execution. It is typically used in cases like method overloading where the specific method to call is known at compile time . Late binding, a run-time process, links method calls to actual method definitions when the program is executed. This is used in scenarios involving method overriding, such as in polymorphism, where the method to execute depends on the actual object . Early binding is preferred for efficiency when possible, while late binding offers flexibility particularly useful for dynamic polymorphic scenarios.

You might also like