Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

Arya College of Enginerring

3CS4-06 -OBJECT ORIENTED PROGRAMMING


2nd year(3rd semester)
(Guess Paper)
Unit 1
(Part A)
Q1.Define object oriented programming?
OOP is an approach that provides a way of modularizing programs by creating
partitioned memory areas for both data and functions that can be used as an
templates for creating copies of such modules on demand.

Q2.List some features of OOP?


Emphasis is on data rather than procedures.
Programs that are divided into what are known as objects.
Follows bottom – up approach in program design.
Functions that operate on the data of an object are tried together in the data
structure.

Q3.Define Class?
A Class is a collection of objects of similar type.
The classes are user-defined data types and behave like built-in types of a
programming language.
A class is a way to bind the data and its associated functions together.
A class is a user-defined data type with a template that serves to define its properties.
A class is a blueprint that defines the variables & the methods common to all objects
of a certain kind.

Q4.What do you mean by object?


Objects are basic run-time entities in an object-oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the
program has to handle. Each object has the data and code to manipulate the data
and theses objects interact with each other.

Q5.What is meant by Encapsulation?


The wrapping up of data and function into a single unit(class) is known as
Encapsulation.
Q6.What do you mean by Data abstraction?
Abstraction refers to the act of representation of essential features without including
the background details or explanations. Classes use the concept of abstraction & are
defined as a list of abstraction attributes such as size, weight & cost & functions to
operate on these attributes.

Q7.Define polymorphism?
Polymorphism means the ability to take more than one form. For example, an
operation may exhibit different behavior in different instances. The behavior depends
upon the types of data used in the operation.

Q8.List out the benefits of OOPS.


Through inheritance, we can eliminate redundant code and extend the use of existing
classes.
The principle of data hiding helps the programmer to build secure programs.
It is possible to have multiple instances of an object to co-exist without any
interference.
Object oriented systems can be easily upgraded from small to large systems.
Software complexity can be easily managed.
Part B
Q1.Expalin the concept array of object?
An array in C/C++ or be it in any programming language is a collection of similar data
items stored at contiguous memory locations and elements can be accessed
randomly using indices of an array. They can be used to store the collection of
primitive data types such as int, float, double, char, etc of any particular type. To add
to it, an array in C/C++ can store derived data types such as structures, pointers, etc.
Given below is the picture representation of an array.
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.

Example

#include<iostream>
using namespace std;

class Employee
{
int id;
char name[30];
public:
void getdata();//Declaration of function
void putdata();//Declaration of function
};
void Employee::getdata(){//Defining of function
cout<<"Enter Id : ";
cin>>id;
cout<<"Enter Name : ";
cin>>name;
}
void Employee::putdata(){//Defining of function
cout<<id<<" ";
cout<<name<<" ";
cout<<endl;
}
int main(){
Employee emp; //One member
emp.getdata();//Accessing the function
emp.putdata();//Accessing the function
return 0;

Q2.Explain different Access specifiers?


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++:
1. Public
2. Private
3. Protected

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.
2. Private: The class members declared as private can be accessed only by the
member functions inside the class. They are not allowed to be accessed directly
by any object or function outside the class. Only the member functions or
the friend functions are allowed to access the private data members of the class.

3.Protected: The protected access modifier is similar to the private access


modifier in the sense that it can’t be accessed outside of its class unless with the
help of a friend class. The difference is that the class members declared as
Protected can be accessed by any subclass (derived class) of that class as well.

Q3.Explain the characteristics of oops?

Object-oriented programming – As the name suggests uses objects in programming.


Object-oriented programming aims to implement real-world entities like inheritance,
hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together
the data and the functions that operate on them so that no other part of the code can
access this data except that function.
There are some basic concepts that act as the building blocks of OOPs i.e.
1. Class
2. Objects
3. Encapsulation
4. Abstraction
5. Polymorphism
6. Inheritance
7. Dynamic Binding
8. Message Passing
Q4.Define Compile time polymorphism / Early Binding / static Binding
Compile time polymorphism is implemented by using the overloaded functions
and overloaded operators.
The overloaded operators or functions are selected for invokation by matching
arguments both by type and number. This information is known to the compiler at
the compile time therefore the compiler is able to select the appropriate function for
a particular function call at the compile time itself. This is called as „Early
Binding‟ or
„Static Binding‟ or „Static Linking‟ or „Compile time polymorphism‟. Early binding
simply means an object is bound to its function call at the compile time.

Q5.What do you mean by reusability?


The process of adding additional features to an existing class without modifying it is
known as „Reusability‟. The reusability is achieved through inheritance. This is
possible by deriving a new class from an existing class. The new class will have the
combined features of both the classes.

Unit 2
Part I
Q1.Define constructor.?

A constructor is a special member function whose task is to initialize the objects

of its class. It is special because its name is same as class name. The

constructor is invoked whenever an object of its associated class is created. It

is called constructor because it constructs the values of data members of the

class
Q2.Differentiate Structure and Classes?

Structures Classes
1. By default the members 1.By default the members of
of the Class are
structure are public. private.
2. Data hiding is not 2.Data hiding is possible
possible
3.sturcture data type 3.Objects can be treated like
cannot be built-in-
treated like built-in-type types by means of operator
overloading.
4.Structure are used 4. Classes are used to hold
only for data and
holding data functions
5.Keyword „struct‟ 5.Keyword „class‟

Q3. What are the special characteristics of a friend function?


 It is not in the scope of the class to which it has been declared as friend.
 Since it is not in the scope of the class, it cannot be called using the object
of the class.
 It can be invoked like a normal function without the help of any object
 Unlike member functions it cannot access the member names directly and
has to use an object name and dot membership operator with each
member name
 Usually it has the object as arguments.

Q4.Explain the concept of new and delete keyword?


In C++ programming language, the new and delete operators are mainly utilized
for dynamic memory allocation and deallocation. They enable us to dynamically
allocate and free the memory, which means that we can create objects whose size and
lifetime may be defined at runtime. However, there are some main distinctions between
the two operators that we should be aware of. In this article, we will explore the
differences between new and delete in C++.
Q5.Explain default argument?
A default argument is a value provided in a function declaration that is automatically
assigned by the compiler if the calling function doesn’t provide a value for the
argument. In case any value is passed, the default value is overridden.
// CPP Program to demonstrate Default Arguments
#include <iostream>
using namespace std;

// A function with default arguments,


// it can be called with
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z = 0, int w = 0) //assigning default values to z,w as 0
{
return (x + y + z + w);
}

// Driver Code
int main()
{
// Statement 1
cout << sum(10, 15) << endl;

// Statement 2
cout << sum(10, 15, 25) << endl;

// Statement 3
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
Q6.What is a destructor?
Destructor is an instance member function that 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.
 A destructor is also a special member function like a constructor. Destructor
destroys the class objects created by the constructor.
 Destructor has the same name as their class name preceded by a tilde (~) symbol.
 It is not possible to define more than one destructor.
 The destructor is only one way to destroy the object created by the constructor.
Hence destructor can-not be overloaded.
 Destructor neither requires any argument nor returns any value.
 It is automatically called when an object goes out of scope.
 Destructor release memory space occupied by the objects created by the
constructor.
 In destructor, objects are destroyed in the reverse of an object creation.
Part-II
Q1.Difference between Constructor and Destructor?
S.
No. Constructor Destructor

Constructor helps to initialize the object of a Whereas destructor is used to destroy


1.
class. the instances.

It is declared as className( arguments if Whereas it is declared as ~


2.
any ){Constructor’s Body }. className( no arguments ){ }.

Constructor can either accept arguments or


3. While it can’t have any arguments.
not.

A constructor is called when an instance or It is called while object of the class is


4.
object of a class is created. freed or deleted.

Constructor is used to allocate the memory to While it is used to deallocate the


5.
an instance or object. memory of an object of a class.

6. Constructor can be overloaded. While it can’t be overloaded.

Here, its name is also same as the


The constructor’s name is same as the class
7. class name preceded by the tiled (~)
name.
operator.

While in a class, there is always a


8. In a class, there can be multiple constructors.
single destructor.

There is a concept of copy constructor which


While here, there is no copy destructor
9. is used to initialize an object from another
concept.
object.

Q2.Explain Function Overloading?


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++.
If multiple functions having same name but parameters of the functions should be
different is known as Function Overloading.
If we have to perform only one operation and having same name of the functions
increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the function such as a(int,int) for two parameters,
and b(int,int,int) for three parameters then it may be difficult for you to understand the
behavior of the function because its name differs.

Function overloading means we can use the same function name to create

functions that perform a variety of different tasks.

Eg: An overloaded add ( ) function handles different data types as shown below.

// Declarations

iv. int add( int a, int b); //add function with 2 arguments of same type

v. int add( int a, int b, int c); //add function with 3 arguments of same type

vi. double add( int p, double q); //add function with 2 arguments ofdifferent type

//Function calls i. add

(3 , 4);

ii. add (3, 4, 5);

iii. add (3 , 10.0);

Q3.Explain the concept of Friend function and friend class?

A friend class can access private and protected members of other classes in which it
is declared as a friend. It is sometimes useful to allow a particular class to access
private and protected members of other classes. For example, a LinkedList class may
be allowed to access private members of Node.

#include <iostream>
using namespace std;
class GFG {
private:
int private_variable;

protected:
int protected_variable;

public:
GFG()
{
private_variable = 10;
protected_variable = 99;
}

// friend class declaration


friend class F;
};
class F {
public:
void display(GFG& t)
{
cout << "The value of Private Variable = "
<< t.private_variable << endl;
cout << "The value of Protected Variable = "
<< t.protected_variable;
}
};

// Driver code
int main()
{
GFG g;
F fri;
fri.display(g);
return 0;
}
Friend Function
Like a friend class, a friend function can be granted special access to private and
protected members of a class in C++. They are the non-member functions that can
access and manipulate the private and protected members of the class for they are
declared as friends.

If a function is defined as a friend function in C++, then the protected and private data
of a class can be accessed using the function.

By using the keyword friend compiler knows the given function is a friend function.

For accessing the data, the declaration of a friend function should be done inside the
body of a class starting with the keyword friend.

Q4.Explain types of Function overloading?


Types of overloading in C++ are:

Function overloading

Operator overloading

C++ Function Overloading

Function Overloading is defined as the process of having two or more function with the
same name, but different in parameters is known as function overloading in C++. In
function overloading, the function is redefined by using either different types of
arguments or a different number of arguments. It is only through these differences
compiler can differentiate between the functions.

The advantage of Function overloading is that it increases the readability of the


program because you don't need to use different names for the same action.

1. #include <iostream>
2. using namespace std;
3. class Cal {
4. public:
5. static int add(int a,int b){
6. return a + b;
7. }
8. static int add(int a, int b, int c)
9. {
10. return a + b + c;
11. }
12. };
13. int main(void) {
14. Cal C; // class object declaration.
15. cout<<C.add(10, 20)<<endl;
16. cout<<C.add(12, 20, 23);
17. return 0;
18. }
C++ Operators Overloading
Operator overloading is a compile-time polymorphism in which the operator is
overloaded to provide the special meaning to the user-defined data type. Operator
overloading is used to overload or redefines most of the operators available in C++. It
is used to perform the operation on the user-defined data type. For example, C++
provides the ability to add the variables of the user-defined data type that is applied to
the built-in data types.
Rules for Operator Overloading
o Existing operators can only be overloaded, but the new operators cannot be
overloaded.
o The overloaded operator contains atleast one operand of the user-defined data
type.
o We cannot use friend function to overload certain operators. However, the
member function can be used to overload those operators.
o When unary operators are overloaded through a member function take no explicit
arguments, but, if they are overloaded by a friend function, takes one argument.
o When binary operators are overloaded through a member function takes one
explicit argument, and if they are overloaded through a friend function takes two
explicit arguments.

#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++() {
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}

Q5. Explain about inline function?


An inline function is a function that is expanded in line when it is invoked. That
is compiler replaces the function call with the corresponding function code.The
inline functions are defined as
Inline function-header

function body

The situations where inline expansion may not work are

• for functions returning values, if loop, a switch, or a goto exists

• for functions not returning values ,if a return statement exists

• if function contain static variables

• if inline functions are recursive


Unit 3
Part I
Q1.Explain inheritance.
Inheritance is the process by which objects of one class acquire the properties of another

class. It supports the concept of hierarchical classification. It provides the idea of reusability.

We can add additional features to an existing class without modifying it by deriving a new

class from it.

Q2.Explain Multiple Inheritance?


Multiple Inheritance is a feature of C++ where a class can inherit from more than one
classes. The constructors of inherited classes are called in the same order in which
they are inherited. For example, in the following program, B’s constructor is called
before A’s constructor.
A class can be derived from more than one base class.
Eg:
(i) A CHILD class is derived from FATHER and MOTHER class
(ii) A PETROL class is derived from LIQUID and FUEL class.

Q3.Explain the concept of Virtual base class?


Virtual base classes are used in virtual inheritance in a way of preventing multiple
“instances” of a given class appearing in an inheritance hierarchy when using multiple
inheritances.
Need for Virtual Base Classes: Consider the situation where we have one class A .
This class A is inherited by two other classes B and C. Both these class are inherited
into another in a new class D as shown in figure below.

Q4.Explain the concept of function overriding?


A function is a block of statements that together performs a specific task by taking
some input and producing a particular output. Function overriding in C++ is termed
as the redefinition of base class function in its derived class with the same signature
i.e. return type and parameters. It falls under the category of Runtime Polymorphism.

Q5.Explain Pure virtual Function?


A pure virtual function (or abstract function) in C++ is a virtual function for which we
can have an implementation, But we must override that function in the derived class,
otherwise, the derived class will also become an abstract class. A pure virtual
function is declared by assigning 0 in the declaration.

Q6.What is abstract class?

An abstract class is one that is not used to create objects. An abstract class is
designed only to act as a base class. It is a design concept is program development
and provides a base upon which other classes may be built.
Part-II
Q1.Explain Inheritance and its Types?
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.
Types of Inheritance
C++ Single Inheritance
Single inheritance is defined as the inheritance in which a derived class is inherited
from the only one base class.

Where 'A' is the base class, and 'B' is the derived class.

C++ Multilevel Inheritance


Multilevel inheritance is a process of deriving a class from another derived class.

When one class inherits another class which is further inherited by another class, it is
known as multi level inheritance in C++. Inheritance is transitive so the last derived
class acquires all the members of all its base classes.

C++ Multiple Inheritance


Multiple inheritance is the process of deriving a new class that inherits the attributes
from two or more classes.

C++ Hybrid Inheritance


Hybrid inheritance is a combination of more than one type of inheritance.

Q2.Difference between Virtual and Pure virtual function?


Virtual function Pure virtual function

A pure virtual function is a member function of base


A virtual function is a member function of
class whose only declaration is provided in base
base class which can be redefined by
class and should be defined in derived class
derived class.
otherwise derived class also becomes abstract.
Virtual function Pure virtual function

Classes having virtual functions are not Base class containing pure virtual function
abstract. becomes abstract.

Syntax:

Syntax:
virtual<func_type><func_name>()

{ virtual<func_type><func_name>()

// code = 0;

Definition is given in base class. No definition is given in base class.

Base class having virtual function can be Base class having pure virtual function becomes
instantiated i.e. its object can be made. abstract i.e. it cannot be instantiated.

If derived class do not redefine virtual function of


If derived class do not redefine virtual
base class, then no compilation error but derived
function of base class, then it does not
class also becomes abstract just like the base
affect compilation.
class.

All derived class must redefine pure virtual function


All derived class may or may not
of base class otherwise derived class also becomes
redefine virtual function of base class.
abstract just like base class.

Q3.What is function overriding Explain with example?


A function is a block of statements that together performs a specific task by taking
some input and producing a particular output. Function overriding in C++ is termed
as the redefinition of base class function in its derived class with the same signature
i.e. return type and parameters. It falls under the category of Runtime Polymorphism.

// C++ program to demonstrate function overriding

#include <iostream>
using namespace std;

class Parent {
public:
void GeeksforGeeks_Print()
{
cout << "Base Function" << endl;
}
};

class Child : public Parent {


public:
void GeeksforGeeks_Print()
{
cout << "Derived Function" << endl;
}
};

int main()
{
Child Child_Derived;
Child_Derived.GeeksforGeeks_Print();
return 0;
}
Q4.How ambiguity is resolved in inheritance?
In the inheritance when more than one class has a function with the same name and same type signature, then there exists
ambiguity. It can be solved by using the class resolution operation with the function

Q5.WAP to use the concept of multiple inheritance ?


#include<iostream>
using namespace std;

class A
{
public:
A() { cout << "A's constructor called" << endl; }
};

class B
{
public:
B() { cout << "B's constructor called" << endl; }
};

class C: public B, public A // Note the order


{
public:
C() { cout << "C's constructor called" << endl; }
};

int main()
{
C c;
return 0;
}

Unit 4
Part-I
Q1.Define Runtime Polymorphism?
At runtime, when it is known what class objects are under consideration, the
appropriate version of the function is invoked. Since the function is linked with a
particular class much later after its compilation, this process is termed as „late binding‟.
It is also known as dynamic binding because the selection of the appropriate function is
done dynamically at run time. This runtime polymorphism can be achieved by the use
of pointers to objects and virtual functions
Q2.What is dynamic binding?
Dynamic binding in C++ is a practice of connecting the function calls with the function
definitions by avoiding the issues with static binding, which occurred at build time.
Because dynamic binding is flexible, it avoids the drawbacks of static binding, which
connected the function call and definition at build time.
Q3.Explain virtual function?
A virtual function (also known as virtual methods) is a member function that 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 method.
 Virtual functions ensure that the correct function is called for an object, regardless
of the type of reference (or pointer) used for the function call.
 They are mainly used to achieve Runtime polymorphism.
 Functions are declared with a virtual keyword in a base class.
 The resolving of a function call is done at runtime.

Q4.Explain about Operator Overloading?

C++ has the ability to provide the operators with a special meaning for a data
type. This mechanism of giving such special meanings to an operator is known
as Operator overloading. It provides a flexible option for the creation of new
definitions for C++ operators.
The operators that cannot be overloaded are.

• Class member access operator (. , .*)

• Scope resolution operator (::)

• Size operator ( size of )

• Conditional operator (?:)

The purpose of using operator function is to define an additional task to an operator,


we must specify what it means in relation to the class to which the operator is applied
Q5.Explain Static data member?

When we define the data member of a class using the static keyword, the data
members are called the static data member. A static data member is similar to the
static member function because the static data can only be accessed using the static
data member or static member function. And, all the objects of the class share the
same copy of the static member to access the static data.

Part-II
Q1.Explain Constant data member and member function?
Constant member functions are those functions that are denied permission to change
the values of the data members of their class. To make a member function constant,
the keyword const is appended to the function prototype and also to the function
definition header.
Like member functions and member function arguments, the objects of a class can
also be declared as const. An object declared as const cannot be modified and
hence, can invoke only const member functions as these functions ensure not to
modify the object. A const object can be created by prefixing the const keyword to the
object declaration. Any attempt to change the data member of const objects results in
a compile-time error.
Important Points
 When a function is declared as const, it can be called on any type of object, const
object as well as non-const objects.
 Whenever an object is declared as const, it needs to be initialized at the time of
declaration. however, the object initialization while declaring is possible only with
the help of constructors.
 A function becomes const when the const keyword is used in the function’s
declaration. The idea of const functions is not to allow them to modify the object on
which they are called.
 It is recommended practice to make as many functions const as possible so that
accidental changes to objects are avoided.

Q2.Explain polymorphism and its type in detail?


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. A
real-life example of polymorphism is a person who at the same time can have
different characteristics. A man at the same time is a father, a husband, and an
employee. So the same person exhibits different behavior in different situations. This
is called polymorphism. Polymorphism is considered one of the important features of
Object-Oriented Programming.
Types of Polymorphism
 Compile-time Polymorphism
 Runtime Polymorphism
. Compile-Time Polymorphism
This type of polymorphism is achieved by function overloading or operator
overloading.
A. Function Overloading
When there are multiple functions with the same name but different parameters, then
the functions are said to be overloaded, hence this is known as Function
Overloading. Functions can be overloaded by changing the number of
arguments or/and changing the type of arguments. In simple terms, it is a feature
of object-oriented programming providing many functions that have the same name
but distinct parameters when numerous tasks are listed under one function name.
There are certain Rules of Function Overloading that should be followed while
overloading a function.
B. Operator Overloading
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 make use of the
addition operator (+) for string class to concatenate two strings. We know that the
task of this operator is to add two operands. So a single operator ‘+’, when placed
between integer operands, adds them and when placed between string operands,
concatenates them.
2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late binding and
dynamic polymorphism are other names for runtime polymorphism. The function call
is resolved at runtime in runtime polymorphism. In contrast, with compile time
polymorphism, the compiler determines which function call to bind to the object after
deducing it at runtime.
A. Function Overriding
Function Overriding occurs when a derived class has a definition for one of the
member functions of the base class. That base function is said to be overridden.
B. Virtual Function
A virtual function is a member function that is declared in the base class using the
keyword virtual and is re-defined (Overridden) in the derived class.
Some Key Points About Virtual Functions:
 Virtual functions are Dynamic in nature.
 They are defined by inserting the keyword “virtual” inside a base class and are
always declared with a base class and overridden in a child class
 A virtual function is called during Runtime

Q3.Difference in between static and dynamic binding?


Static Binding Dynamic Binding

It takes place at compile time which is referred It takes place at runtime so it is referred to as
to as early binding late binding

Execution of static binding is faster than Execution of dynamic binding is slower than
dynamic binding because of all the information static binding because the function call is not
needed to call a function. resolved until runtime.

It takes place using normal function calls,


It takes place using virtual functions
operator overloading, and function overloading.

Real objects never use static binding Real objects use dynamic binding
Q4. Explain static data member in detail?
Static data members are class members that are declared using static keywords. A
static member has certain special characteristics which are as follows:
 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 created, even before the main
starts.
 It is visible only within the class, but its lifetime is the entire program .
 The static is a keyword in the C and C++ programming language. We use the
static keyword to define the static data member or static member function inside
and outside of the class. Let's understand the static data member and static
member function using the programs.

// C++ Program to demonstrate


// the working of static data member
#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;
}
Q5.What are the different types of binding of object with pointer?
When you have a pointer to an object, the object may actually be of a class that is
derived from the class of the pointer.
Thus there are two types:
1.Static binding 2. Dynamic binding
Unit 5
Part I
Q1.Differentiate between function template & function overloading.

Function Template Function Overloading


1.Only one function definition 1.several function definitions with the
same function name with different
argument list.

2. Here the data type upon which the function 2.Here the function can operate on only one
operates is passed as parameter data type. For another data type we have to
redefine the function with same
name with different argument list.

3.Program space is less 3.Program space is large


4.Generic function must perform same 4.Different actions can be performed

Q2. What is meant by exception handling?


C++ provides a built-in error handling mechanism called Exception handling.
Exception handling is the subsystem of C++ that allows us to handle errors that occur
at run time in a structured and controlled manner. With exception handling, program
can automatically invoke an error handling routine when an error occurs. The proper
use of exception handling helps to create resilient code.

Q3.What are two types of exceptions?


Exceptions are of two kinds namely
Synchronous : Error such as “out-of-range index” and “overflow”
Asynchronous : errors that are caused by events beyond the control of the
program such as keyboard interrupts.

Q4.How to handle all types of exception?


In some situations, it is not possible to anticipate all possible types of exceptions
and therefore may not possible to design independent catch handlers to catch them.
In such circumstances, a catch statement can be forced to catch all exceptions
instead of certain types alone. This is achieved by defining the catch statement
using
catch(…)
{ statements for processing all exceptions
}
5.Explain exception handling mechanism.
When the try block throws an exception, the program control leaves the try block
and enters the catch statement of the catch block. The exceptions are object used
to transmit information about a problem. If the type of the object thrown matches the
argument type in the catch statement, then the catch block is executed for handling
exception. If they do not match the program is terminated using abort ( ) function.

Part II
Q1.What is templates?
A template is a simple yet very powerful tool in C++. The simple idea is to pass the
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 the datatype as a parameter.
C++ adds two new keywords to support templates: ‘template’ and ‘type name’. The
second keyword can always be replaced by the keyword ‘class’.
Function Templates
We write a generic function that can be used for different data types. Examples of
function templates are sort(), max(), min(), printArray().
Class Templates
Class templates like function templates, class templates are useful when a class
defines something that is independent of the data type. Can be useful for classes like
LinkedList, BinaryTree, Stack, Queue, Array, etc.

// C++ Program to implement

// template Array class

#include <iostream>

using namespace std;

template <typename T> class Array {

private:

T* ptr;

int size;

public:

Array(T arr[], int s);

void print();

};
template <typename T> Array<T>::Array(T arr[], int s)

ptr = new T[s];

size = s;

for (int i = 0; i < size; i++)

ptr[i] = arr[i];

template <typename T> void Array<T>::print()

for (int i = 0; i < size; i++)

cout << " " << *(ptr + i);

cout << endl;

int main()

int arr[5] = { 1, 2, 3, 4, 5 };

Array<int> a(arr, 5);

a.print();

return 0;

}
Q2.What is the difference between function overloading and templates?
Both function overloading and templates are examples of polymorphism features of
OOP. Function overloading is used when multiple functions do quite similar (not
identical) operations, templates are used when multiple functions do identical
operations.

Q3.Explain Exceptional handling with Keywords?


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.


The try statement allows you to define a block of code to be tested for errors while it
is being executed.

catch: Represents a block of code that is executed when a particular exception is


thrown.
The catch statement allows you to define a block of code to be executed if an error
occurs in the try block.
throw: Used to throw an exception. Also used to list the exceptions that a function
throws but doesn’t handle itself.
The throw keyword throws an exception when a problem is detected, which lets us
create a custom error.

Q4.What is File Handling in C++?

File handling in C++ is a mechanism to store the output of a program in a file and help
perform various operations on it. Files help store these data permanently on a storage
device.

To read and write from a file we are using the standard C++ library called fstream. Let
us see the data types define in fstream library is:

Data Type Description

fstream It is used to create files, write information to files, and read information
from files.
ifstream It is used to read information from files.

ofstream It is used to create files and write information to the files.


#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream filestream("testout.txt");
if (filestream.is_open())
{
filestream << "Welcome to javaTpoint.\n";
filestream << "C++ Tutorial.\n";
filestream.close();
}
else cout <<"File opening is fail.";
return 0;
}
C++ FileStream example: reading from a file
1. #include <iostream>
2. #include <fstream>
3. using namespace std;
4. int main () {
5. string srg;
6. ifstream filestream("testout.txt");
7. if (filestream.is_open())
8. {
9. while ( getline (filestream,srg) )
10. {
11. cout << srg <<endl;
12. }
13. filestream.close();
14. }
15. else {
16. cout << "File opening is fail."<<endl;
17. }
18. return 0;
19. }
Q5. C++ Stream Classes?
In C++ there are number of stream classes for defining various streams related with
files and for doing input-output operations. All these classes are defined in the
file iostream.h. Figure given below shows the hierarchy of these classes.

1. ios class is topmost class in the stream classes hierarchy. It is the base class
for istream, ostream, and streambuf class.

2. istream and ostream serves the base classes for iostream class. The
class istream is used for input and ostream for the output.

3. Class ios is indirectly inherited to iostream class using istream and ostream. To
avoid the duplicity of data and member functions of ios class, it is declared as
virtual base class when inheriting in istream and ostream as

Facilities provided by these stream classes.

1. The ios class: The ios class is responsible for providing all input and output
facilities to all other stream classes.

2. The istream class: This class is responsible for handling input stream. It provides
number of function for handling chars, strings and objects such as get, getline,
read, ignore, putback etc..

You might also like