C++ programming
C++ programming
56 | P a g e
Q) What different data types in C++? Explain it detail?
The data type is requires in every variable, function, array, string, pointer declarations. The data
type name suggest that it decides the type of variable, function, array, string, pointer etc. It also decides
how much space it reserves in memory. It holds decides which data that variable, function, array, string,
pointer etc holds during the program execution.
The data type in C++ is classified into three groups
such as follows : SrNo Data type Bytes
1) Built in type OR basic data type OR primary data type. OR
i) Integral type : -It includes integer and character data. Size
They are two types such as follows : 1 signed char 1
a) int : - An int type occupies 2 bytes in memory and holds 2 unsigned char 1
integer constants i.e. whole numbers only. 3 short int 2
b) char : The char type occupies 1 byte in memory and OR
holds character data. signed int
i) Floating type :- 4 unsigned int 2
It holds floating constants or real numbers. The 5 Float 4
constants are contains decimal point numbers. They 6 Double 8
are two types such as follows: 7 long double 10
a) float : - The float type occupies 4 byte in memory and holds real constant i.e. constant have decimal
point.
b) double :- The double type occupies 8 byte in memory and holds real constants or fractional numbers.
ii) void type :- void data type is used in following ways :
a) To specify the return type of a function when it is not returning any value.
b) To indicate an empty argument list to a function.
c) To declare generic pointer.
2) Secondary data type OR Derived data type: These are derived from primary data type.
i) Array ii) Function iii) Pointer iv) String
3) User Defined data type OR Abstract type
C++ allows user to creates a new abstract data types which can behaves like any built in data type.
These are called as user defined data types. These includes structure, union, class and enumeration etc.
i) Class ii) Structure and Union and Enumeration
57 | P a g e
Q) Explain memory management operators used in C++ ?
There are two types of memory management operators is used in C++ is called as new and delete
operators.
1) new : - It is a memory management operator used to allocates a memory in memory location. It
is also used for dynamic storage allocation. This operator can be used to creates object of any
type.
Syntax : pointer variable = new data type ;
2) delete : - This operator is used for deallocation. This operator releases or free memory space in
memory.
Syntax : delete variable ;
Example :
void main ( )
{
int *a = new int ;
*a = 100 ;
cout<<”\nUsing new operator”<<*a ;
delete a ;
}
Q) What is function in C++ write a suitable example.
A self contained block of statement or collection statements in its block is called as function. The
function block is written separately i.e. defined separately from main () but before definition they are
declared at outside the main function.
Terms related to functions :
1) Function prototype : -
This a statement declared outside the main function i.e. above main ( ) from this statement function are
identified. This is also known as function declaration.
Syntax : return type functionname (type argument1, type argument2,…., type argument n) ;
In above syntax return type of function is either char/int/float/double/void etc each arguments or parameters
in function have its own data type either char/int/float/double etc.
2) Function definition :
This is a collection of statement of function. It tells that how function is implemented i.e what function is do
is defined in this block. The function definition block is defined outside main ( ).
3) Function call :
This a statement is used in main ( ) . The main ( ) function calls subfunction is given in function call
statement.
Example :
void add ( int a, int b ); // function prototype of declaration
void main ( )
{
int a=10;
int b = 20 ;
cout<<”\nEnters two numbers”;
cin>>a>>b;
add(a,b); // function call
getch() ;
}
void add ( int a, int b ) // function definition
{
int c ;
c=a+b;
cout<<”\n”<<c;
}
58 | P a g e
Q) Explain the concept of function overloading with suitable example.
More than one function name having the same name but different task is called as function
overloading. Overloading refers to the use of same thing for different purposes. It is also called as function
polymorphism or compile time polymorphism.
In this C++ compiler finds more than one function have same name thus appropriate function is
selected for execution in function call is dependent on number of arguments is given with function call, type
of argument used in functions.
Thus in functions use different data types for arguments and number of arguments are different i.e
same data type and same arguments are used in two functions then ambiguity is occurred thus no any
functions are executed.
Example
int area ( int x ) ;
int area ( int a, int b );
void main ( )
{
cout<<area ( 10 );
cout<<area ( 2 ,4 );
}
int area ( int x )
{
return (x * x ) ;
}
int area ( int a , int b )
{
return ( a+b) ;
}
In above example the function area ( ) is overloaded. When a function s called then C++ compiler
first matches the arguments given in call and its type. If match is found then appropriate function is select
for execution.
In above example both area ( ) have different argument numbers one has one argument other has
two arguments. This area ( ) have same type argument as integer but number of arguments are different so
overloading function are not ambiguity in execution. If two function have same argument type and same
number of argument then overloading function can not executes function.
59 | P a g e
Q) Explain in detail inline function? What are different situations in which compiler may ignore
inline request?
An inline function is a function that is expanded inline when it is invoked or initiated. The C++
compiler replaces function call with the corresponding function code.In inline function inline keyword is used
with function name.
Example
inline int area ( int a, int b )
{
return ( a*b ) ;
}
In above example inline keyword is used before function return type and function name.
Following are some situations in which compiler may ignore inline request :
1) For functions returning value then inline request is ignored.
2) The program contains loop statements, switch case statement or goto statements then inline
request is ignored.
3) For function not returning value i.e. if a return statement is exists then inline request is ignored.
4) If function contains static variables then inline request is ignored.
5) If function contains recursion then inline request is ignored.
60 | P a g e
Q) Explain use of pointer variables for function definitions using call by value and call by
reference.
OR Explain call by value and call by reference with one example of each.
The use of pointers in a function definition may be classified into two groups :
1) Call by value 2) Call by reference
1) Call by value :-When function is called in main ( ) then program control is transferred from the main
function to the calling function the main ( ) transfers actual values that are copied to calling function. Within
calling function i.e. sub function the actual values are changed or altered. Then when function is return from
that function to main ( ) back then the altered values or changed values in sub function can not transfers to
main ( ). This mechanism is called call by value because main ( ) calls calling function i.e. sub function by
passing its actual values.
void add ( int a, int b ) ;
void main ( )
{
int a=10 , b = 20;
add ( a,b) ; // function call with call by value i.e. it passes actual value of a and b
getch () ;
}
void add ( int a, int b )
{ a =a + 10 ; // change values of in this function as a=20
b= b + 20 ; // change value of b in this function as b= 40
cout <<”a=”<<a<<”b=”<<b;
}
Thus in above example when program control is transferred from main ( ) to calling function add ( )
then main function passes values of a and b that are copied to calling function i.e. sub function. In calling
function i.e. sub function the values are changed or altered but when it transferred back to main ( ) function
the change in sub function can not passed by sub function to main ( ).
2) Call by reference :-When function is called in main ( ) then program control is transferred from the main
function to the calling function the main ( ) transfers address of the actual arguments that are copied to
calling function. Within calling function i.e. sub function the actual values are changed or altered. Then
when function is return from that function to main ( ) back then the altered values or changed values in sub
function can transfers to main ( ). This mechanism is called call by reference because main ( ) calls calling
function i.e. sub function by passing addresses or references of actual values.
void add ( int *a, int *b ) ;
void main ( )
{
int a=10 ;
int b = 20;
add ( &a,&b) ; // function call with call by reference i.e. it passes address or reference
// of actual value of a and b
getch () ;
}
void add ( int *a, int *b )
{
61 | P a g e
Q)What is array in C++?
An array is a collection of similar type data elements which are stored in consecutive or contiguous
memory locations under common variable name. Array may be one dimensional or multidimensional.
Example : int a [ 10 ] // a is array of integer type holds 10 integer elements under common name
Generally C++ arrays are zero based. In above example the first array element has index 0 and it is
referred as a [ 0 ]. Similarly second array element is a [ 1 ] and last i.e. 10th element is a [ 9 ]. Thus first
element of array is index 0 and last element is size – 1.The subscript tells that variable is array and it have
contain size of array.
Q) What is string in c++ ? Explain various string functions in C++ with example.
The one dimensional character array is called as string in C++. The string are used to manipulates
text as such as words and sentences.
A string constant is 1D array of character terminated by null or \0.
Example : char a [ ] = { “india” } ; // where a is 1D character array is called string which holds string india.
Different string functions
The string functions in C++ are included or predefined into string.h header file. The string functions
such as strlen ( ), strcpy ( ), strcat ( ), strcmp ( ) and strrev ( ) etc. Thus to use this string functions string.h
header file is included in program.
1) strlen ( ) This a string function counts the number of characters are present in string.
2) strcpy ( ) :- This a string function copies the contents of one string i.e. source string into other string i.e.
target string.
3) strcat ( ) :- This a string function concatenates or combines the one string i.e. source string at the end of
another string i.e. target string.
4) strrev ( ) :- This a string function that reverses contents of entered string.
Example:
#include <iostream.h>
#include<conio.h>
#include<string.h>
void main ( )
{
clrscr ( ) ;
char a [80] , b[80] ;
cout<<”\nEnter string”;
cin.getline(a,80);
cout<<strlen(a) ;
cout<<strcpy(b,a) ;
cout<<strcat(a,b) ;
cout<<strrev(a) ;
cout<<strcmp(a,b) ;
getch( ) ;
}
Q) What are different features provided by c-string in C++?
The string provides following features when it is used in program.
1) A string is a sequence of characters array with null terminated character or \0 is used to stores
and
manipulates the string.
2) For each character string in C++ inserts the null character or \0 automatically.
3) Each character in an array is occupied 1 byte of memory.
4) Elements of c-strings are stored in contiguous memory or consecutive memory locations.
62 | P a g e
Q) Explain the structure of a general C++ program.
OR Explain structure of object oriented C++ programming model.
Include Files
Class Declaration
Class Function Definition
Main Function Program
Fig Structure of C++ program
A typical C++ program contains four sections such as Include files, Class declaration, Class function
definition and Main function program. These sections may be placed in different code files and then
compiled independently or jointly.
1) Include Files: Any Input/Output functions are predefined into library subroutine files in header file. The all
input/output fuctions such as cin and cout are predefined into iostream.h file. In this way console functions
such as result get without screening and clear screen etc are defined in conio.h file. In this way some real
life functions are predefined into respective header files. So to use this functions without rewriting its
definition again include header files in program.
2) Class Declaration: The class is a abstract datatype. It is begins with class keyword and same like as
basic datatype class are created abstract datatype. The class declaration contains name of class and they
have two members called as data member and member functions. The variables of class are called as data
members while functions of class are called as member function.
3) Class Function Definition: The member functions in a class are called functions of class they performed
given specific task is defined in its class function definition.
4) Main function Program : The actual execution of program is executed from here. It also executes class
and its members.
Q) What is object oriented programming? Enlist the features of object oriented programming.
Definition of OOP:
An object oriented programming is defined as
“ Object oriented programming is an approach that provides a way of modularizing programs by crating
partitioned memory area for both data and functions that can be used as templates for creating copies of
such modules on demand”.
Characteristics or Features of Object Oriented Programming:
1) Emphasis is on data rather than procedure. 2) Programs are divided into number of entities called as
objects. 3) Data structures are designed such that they characterized the objects.
4) Functions that operates on the data of an object are tied together in the data structure.
5) Data is hidden and can not be accessed by external functions. 6) Objects may communicate with each
other through functions. 7) New data and functions can be easily added wherever required.
63 | P a g e
Q) Explain the OOPS concept with an example of each.
The followings are some object oriented concepts these are used to develops object oriented programming
:
1) Class : -
i) A class is a way to binds data and its associated functions together. ii) A class is a collection of an objects
of similar type.iii) A class is an abstract data type (ADT) or user defined data type in object oriented
programming. Whose variable is object.
2) Object :-
i) An object are runtime entities which are used at run time or dynamically. ii) To combines data and
procedure a unit is formed which operates on that data. This unit is called as object. iii) When program is
executed then object passes messages between them. iv) The object is declared and defined in main ( )
function.
Example : void main ( )
{
xyz d ; // xyz is a class and d is object class is data type and object is variable
d.print ( ) ;
In above example object have dot operator which separates object name and
member function. It is called as object identity operator or membership operator. The
member functions of class only accessible by object.
3) Data Abstraction :-
i) The collection of data and functions in a class is called as data abstraction. ii) The class binds data and
associated functions together is called abstraction. iii) Abstraction refers to the act of representing essential
features without including the background details of explanations. The class are concept of abstraction.
4) Dynamic binding:-
i) The member functions are called at runtime only by an object in main function. This mechanism is called
as dynamic binding. Class binds data and functions together while object are accessed member functions
of class. ii)This technique is associated with polymorphism and inheritance.
5) Data Encapsulation :-
i) The wrapping of data and code i.e. functions into a single unit i.e. class is called as data encapsulation.
ii) Those functions are accessible which is wrapped in a class. An external function can not accesses
outside class is called data hiding.
6) Polymorphism :-
i) An ability to take more than one form is called as polymorphism. ii) They are two types compile time and
runtime. iii) The compile time polymorphism is achieved by function overloading and operator overloading.
iv) The runtime polymorphism is achieved by virtual function.
7) Inheritance :-
i) The mechanism of deriving a new class from base class is called as inheritance.
ii) They are five types single, multiple, multilevel, hierarchical and hybrid.
8) Message Passing :-
i) This is technique by which an object sends and receives messages one to another.
ii) Messages is a request for execution of procedure. iii) Object passes messages from one to another.
Q) What do you mean by object based programming and object oriented programming languages.
State relationship between them.
Object based programming language :-
It supports encapsulation and object identity without supporting important features of object oriented
programming language such as polymorphism, inheritance and message based communication.
Example : Ada is object based programming language.
Object oriented programming language :-
It incorporates all the features of object based programming along with inheritance and
polymorphism.
Example : C++ and Smalltalk are object oriented programming language.
Relationship between object based and object oriented programming language :-
The following expression tells the relationship between object based and object oriented
programming language.
1) Object based programming language = encapsulation + object identity.
2) Object oriented programming language=object based features + Inheritance +
Polymorphism
64 | P a g e
Q) What is class? Explain general form of class declaration.
Class is a way to bind data and its associated functions together. It allows the data and functions to
be hidden if necessary from external use. When defining a class a new abstract data type that can be
created that treated like any other built in data type.
Class specification or syntax of class :
Generally a class specification has two parts such as class declaration and class function definition.
1) Class Declaration: The class declaration describes the type and scope of its members.
Syntax or Form of Class Declaration:
class classname
{
visibility label: Declaration of variables
visibility label: Declaration of member functions
};
In above syntax
i) The keyword class specifies that what follows is an abstract data type class-name.
ii) The body of a class is enclosed within pair of braces (open and close) and is terminated by a semicolon.
The body of class contains declaration of class members such as:
a) Data Member of class :
The all variables declaration in class body are called as data members of class. They have its own
visibility labels either public or private or protected. The members declared as private can be accessed only
from within the class. It hides data from external use. The public data members can be accessed from
outside the class also. If visibility label are missed or not given then by default its visibility is private.
b) Member function of class :
The all functions in body of class are called as member functions of class. They have its own
visibility labels either public or private or protected. The members declared as private can be accessed only
from within the class. It hides data from external use. The public data members can be accessed from
outside the class also. If visibility label are missed or not given then by default its visibility is private.
2) Class function definition:
The class function definition describes how class functions are implemented. Class member
functions are defined outside the class definition and inside the class definition.
65 | P a g e
Q) Describe how member functions of class can be defined outside the class definition and inside
the
class definition.
Member functions of class can be defined as two ways:
1) Inside the class definition :When a function is defined inside a class is called as inside class definition. It
is treated same like inline function.
Syntax : class class name
{
visibility label : return type function name ( )
{
// body of function
}};
Example :
class addition
{
public: int a, b, c;
public : void add ( )
{
c= a + b ;
cout<<”\n Sum=”<<c ;
}
};
}
Example :
class addition
{
public: int a, b, c;
public : void add ( ) ;
};
void addition : : add ( )
{
c= a + b ;
cout<<”\n Sum=”<<c ;
}
66 | P a g e
Q) What is an object? Describe how members of a class be accessed using object of that class.
An object is a variable whose data type is class. In one class more than one object are possible to
declares. The declaration of an object is similar to that of a variable of any basic type. The necessary
memory space is allocated to an object at this stage. Each object of class are declared and defined only in
main function.
Syntax : class-name object1-name, object2-name, -------- , object-n-name ;
Accessing members of a class using objects :
Each of member functions and data members are accessed by object. For this object uses dot
operator between object name and function name. The dot operator or period connects the object name
and the member function. The dot operator is also called as class member access operator.
Example
class addition
{
public: int a, b, c;
public : void add ( ) ;
};
void addition : : add ( )
{
c= a + b ;
cout<<”\n Sum=”<<c ;
}
void main ( )
{
addition x;
x.add( ) ;
getch();
}
Where addition x statement in main function is called as addition as class name is data type
and x is object of class. The statement x.add( ) i.e. object x and dot operator separates object and
member function. Thus object accesses member function of class and object must be declared and
defined only in main function and accessed by data type class and variable object and dot operator
with object and member function accesses it s function. Thus member functions of class are
accessed by object.
The public variables of class can be accessed within main ( ). But private variables can not
accessed inside main program they can be accessed by public functions of the same class.
67 | P a g e
Q) Explain three special characteristics of a static data member and static member function in a
class.
Characteristic/properties of Static data member;-
The three special characteristics of a static data member in a class are as follows:
1) It is initialized to zero when the first object of its class is created. No other initialization is permitted.
2) 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.
3) It is visible only within the class but its life time is the entire program.
68 | P a g e
Q) What is constructor? Why it is so called?
A constructor is a special member function of a class. Its task is to initialize the objects of its class. It
is called special member because its name is same as that of the class to which it belongs. The constructor
is initiated or 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. A constructor can never return any value. Hence, it is
written with no return type even void is not written.
Example:
class addition
{
public : int a,b ;
public : addition ( ) ; // constructor is declared name of class = name of constructor
};
addition : : addition ( )
{
m=0 ;
n = 1;
}
void main ( )
{
addition x ; // object is created and it constructs data members
}
In above when object is created then constructor automatically initializes class data member.
Thus in above object x not only creates the object x of tyoe integer but also it initializes its data
members as m=0 and n=1.
Q) What are the syntax rules for writing constructors?
OR Write/Enlist characteristics of a constructor function.
The following are syntax rules to writing constructor these are also called as features or characteristics
of constructor function.
1) The constructor name is same as the class name.
2) They do not have return types not even void and therefore they can not return values.
3) They can not be static or virtual. 4) They should be declared only in public section.
5) They can not be inherited though a derived class can call base class constrictor.
6) Like other C++ functions they can have default arguments.n7) Constructor can not refer to its address.
8) An object with a constructor can not be used as a member of union.
9) They make implicit calls to the operator new and delete when memory allocation is required.
10) When a constructor is declared for a class then initialization of class objects become mandatory. Since
constructor is invoked automatically when the objects are created.
69 | P a g e
Q) What are different forms of constructors in C++? OR Explain different types of constructors.
C++ have various ways to defines constructor such like as follows :
1) Parameterized Constructor : Those constructors can take one or more arguments or parameters
are called as parameterized constructor.
Example : class fib
{
int f0, f1 ; // data members
public: fib( int x , int y ) // parameterized constructor with two arguments
};
2) Non Parameterized Constructor : Those constructors can not take any arguments or parameters are
called as non parameterized constructor.
Example : class fib
{
int f0, f1 ; // data members
public: fib( ) // non parameterized constructor with no arguments
};
3) Default Constructor : Those constructors can take one or more arguments or parameters with
default or constant value from right to left are called as default constructor or dynamic constructor.
Example : class fib
{
int f0, f1 ; // data members
public: fib( int x , int y=2 ) // default constructor y argument contain default value 2.
};
4) Copy constructor :-Copy constructor are always used when the compiler has to creates a temporary
object of a class object.
General form or syntax : class-name : : class-name (class-name &object-name)
Example:
fib : : fib (fib &x ) // copy constructor
{
f0 = x.fo ;
f1 = x.f1 ;
}
70 | P a g e
Q) What is destructor? Write the syntax rules of destructor?
A destructor as name implies is used to destroy or delete the objects that have been created by a
constructor. The destructor is invoked or initialized implicitly by the compiler upon exit from the program to
clean up storage that is no longer accessible.
In other word destructor is defined as “a destructor function gets executed whenever an instance of
the class i..e object of the class to which it belongs goes out of existence.
The destructor is started or begins with tilde sign ( ~) class name. e.g ~fib ( ).
Syntax rules for writing a destructor function:
1) A destructor function name is same as that of its class name. But it is preceded by a tilde sign(~) class
name e.g. ~fib ( ).
2) It is declared with no return type since it can never return any value i.e. do not use even void.
3) It takes no arguments i.e. it does not contains any arguments or parameter.
4) It is public declared and defined.
71 | P a g e
Q) What is operator function? Describe the syntax of an operator function. Explain the
difference between operator function as member function and friend function.
To define an additional task to an operator it specify what it mean in relation to the class to
which the operator is applied. This is done with the help of a special function called as operator
function which describes the task.
In other words “ A function which defines additional task to an operator or which gives a
special meaning to an operator is called as operator function.
Syntax of operator function OR general form of operator function:
return-type class-name : : operator op ( argument list )
{
// operator function body
}
Where return-type is type of value returned by the specified operation is
int/char/float/double/void etc and op is the operator such as ++/- - /+/- etc is being overloaded.
Operator functions must be either member functions i.e. non-static or friend function.
Basic difference between operator function as a friend function and as a member function
72 | P a g e
Q) Write syntax rules for overloading operators.
There are certain restrictions and limitations for overloading operators. Some of them are
listed below:
1) Only existing operators can be overloaded. New operators can not be created.
2) The overloaded operator must have atleast one operand that is user-defined data type.
3) The basic meaning of an operator can not be changed i.e. we can not redefine the plus(+)
operator to subtract one value from the another.
4) The overloaded operators follow the syntax rules of original operators.
5) Following are some operators that can not be overloaded :
Operators Operator Name
Sizeof Size of operator.
. Membership operator.
.* Pointer to member operator.
:: Scope resolution operator.
?: Conditional operator.
6) Following certain operators can not overloaded using friend functions but member functions can be
used to overload them.
Operators Operator Name
= Assignment operator.
() Function call operator.
[] Subscripting operator
Q) Enlist the operators which can not be overloaded and the operators where friend functions
can not be used.
Operators which can not be overloaded as like follows :
Operators Operator Name
Sizeof Size of operator.
. Membership operator.
.* Pointer to member operator.
:: Scope resolution operator.
?: Conditional operator.
73 | P a g e
Q) Write a short note on type conversions.
When constants and variables of different datatypes are mixed in an expression then C++ compiler
applies automatic datatype conversions to the operands as per certain rules. The type of data to the right of
an assignment operator is automatically converted to the type of variable on the left.
An assignment operator also causes the automatic type conversions.
Example:
int x; float y; y=29.13; x = y ;
In above example x=y is type conversion statement it converts y to an integer before its
value is applied to x. Thus the fractional part is truncated or removed because y is converted into
integer value. So its value is 29.
Different types of data conversion in C++ :
The C++ provides three types of data conversions called as :
1) Conversion from built in type to class type. 2) Conversion from class type to built in type.
3) Conversion from one class type to another class type.
1) Conversion from built in type to class type :
In this data conversion constructor can be used for default type conversion from argument‟s
type to the constructor‟s data type.
Example: class time
{
int hr, min;
public : time (int t) // constructor
{
hr=t / 60 ; min = t % 60 ;
}};
void main ( )
{
time z ; // z is object
int duration = 90;
z= duration ; // data conversion int to class type i.e built in type to class type.
2) Conversion from class type to built in type:
In this data conversion overloaded casting operator is used to covert a class type data to basic data type.
Syntax : operator datatypename ( )
{
// function body
}
The conversion function must satisfy the following conditions :
a) It must be a class member. b) It must not specify a return value. c) It must not have any arguments.
Example: time : : operator int ( ) // where time is class operator int ( ) operator function
{
int min ; int min1 = hr * 60 ; min1 = min1 +min; return min1;
}
void main ( )
{
time t ; // t is object class time
int m = t ; // data conversion class to basic data type.
3) Conversion from one class type to another class type :
In this data conversion uses one argument constructor or conversion function depends upon the
defining conversion routine in source class or destination class.
Example:
object a = object b
Where object a is a destination class object and object b is source class object. The
constructor is placed in the destination class and conversion function is placed in source class.
74 | P a g e
Q) What is polymorphism? Explain runtime and compile time polymorphism.
OR What does polymorphism in C++ ? How is the same achieved at :
a) Compile time b) Runtime ?
Polymorphism means one name and multiple forms i.e an ability take multiple forms is called as
Polymorphism.
Types of polymorphism :
There are two types of polymorphism such as
1) Compile time polymorphism :
In this information is known to the c++ compiler at the compile time and therefore the c++ compiler
is able to select the appropriate function for a particular call at the compiler time itself This is known as
compile time polymorphism.
Compile time polymorphism is also known as early binding or static binding. Because an object is
bound to its function at compile time.
Example: Function overloading and operator overloading are called as compile time polymorphism.
In function overloading more than one functions having same name but different task. Thus appropriate
function is selected by its type of argument, number of argument given etc. Thus in operator overloading
one operator overloads other operator.
2) Runtime polymorphism :
In this the member function is to be selected or invoked while the program is running. So this is
called as runtime polymorphism.
In this the appropriate member function can be selected at runtime and it is known as runtime
polymorphism. To achieve this C++ supports mechanism of virtual function is used.
Example : Virtual function.
In this same function name in both base and derived class the function in base class is declared as
virtual using keyword virtual. The c++ compiler determines which function to use at runtime based on the
type of object pointed to by the base pointer.
Q) Write the difference in between static binding and dynamic binding with example.
Static Binding Dynamic Binding
1) An object is bound to its function call at compile 1) Selection of the appropriate function is done
time. dynamically at runtime.
2) The compiler knows the function information i.e. 2) The function is linked with a particular class much
argument type, number of argument etc at the later after the compilation also known as late
compile time itself. So it able to select appropriate binding.
function for a particular call also called as early
binding.
3) Example : 3) Example:
Function overloading, Operator overloading Virtual function
4) class A 4) class A
{ {
int x ; int x ;
public: void show ( ) public: virtual void show ( )
{ {
cout<<”\nBase Class” ; cout<<”\nBase Class” ;
}}; }};
class B : public A class B : public A
{ {
int y ; int y ;
public : void show ( ) public : void show ( )
{ {
cout<<”\nDerived class”; cout<<”\nDerived class”;
} }; } };
75 | P a g e
Q) Explain the concept of virtual function.
When user use the same function name in both the base and derived classes then the function in
base class is declared as virtual using the keyword virtual.
When a function is made virtual then C++ compiler determines which function to use at runtime
based on the type of object pointed to by the base pointer. Thus by making the base pointer to point two
different objects it can execute different versions of the virtual function.
The virtual function can be accessed through the use of a pointer declared as a pointer to the base
class. Since the prototypes of the base class version of a virtual function and all the derived class versions
must be identical.
If two functions with the same name having different prototype then C++ compiler considers them as
overloaded functions and the virtual function mechanism is ignored.
Q) Write basic rules for virtual function that satisfy the compiler requirements.
When virtual functions are created for implementing late binding then following basic rules are
provided by C++ that satisfy compiler requirements:
1) The virtual functions must be members of base class. 2) They can not be static members.
3) They are accessed by using object pointers. 4) A virtual function can be a friend of another class.
5) A virtual in a base class must be defined even though it is not used.
6) The prototype of the base class version of virtual function and all derived class version must be identical.
If two functions have different prototype then C++ compiler considers them as overloaded functions and not
as virtual functions. 7) We can not have virtual constructors but we can have virtual destructors.
8) A base pointer can point to any type of derived object i.e. we can not use a pointer to derived class to
access an object of the base type.
9) When base pointer points to derived class then incrementation and decrementation is only relative to its
base type.
10) Virtual functions are defined in base class they need not be redefined in derived class.
76 | P a g e
Q) Explain different types of inheritances with suitable diagram.
There are five (5) type of inheritances in C++ such as follows :
1) Single Inheritance :
A derived class with only one base class is called as single inheritance.
Base class A
B
Derived Class
2) Multilevel Inheritance :
The mechanism of deriving one class from another derived class is multilevel inheritance.
Base Class A
Derived Class C
3) Multiple Inheritance :
When a class is derived from several base classes then it is called as multiple inheritance.
B1 B2 B3
D
4) Hierarchical Inheritance :
When several derived class are derived from only one base class is known as hierarchical
inheritance.
B Base Class
D1 D2 D3
Derived Classes
5) Hybrid Inheritance :
The inheritance which involves more than one inheritances is called as hybrid inheritance.
Grand Parent B
Parents A C
Child
D
77 | P a g e
Q) What is virtual base class? Why is it necessary to define virtual base classes in some cases
of hybrid inheritance?
Sometimes when hybrid inheritance is used then there are at least three levels as shown in
following figure. In figure.
Grand Parent
B
Parent A C
Child D
In figure class A and C are derived from class B and class D is derived from two parent class
i.e. class A and class C. This means that class D may contains duplicate sets of members of class B
i.e. the members of class B are inherited in class D twice via class A and via class C. This produces
ambiguity. To avoid this ambiguity concept of virtual base class is used.
Thus duplication of inherited members due to multiple paths can be avoided by making the
common base class as virtual base class while declaring the direct or intermediate base classes as
follows:
class B
{
} ; // Grand Parent Class
class A: virtual public B
{
} ; // parent1 class
class C : virtual public B
{
} ; //parent 2 class
Class D : public A, public C //child class
{
} ; // only one copy of B will be inherited.
When a class is made a virtual base class then C++ takes necessary care to see that
only one copy of that class is inherited regardless of how many inheritance path exist between the
virtual base class and the derived class.
Q) What are input and output streams?
The I/O system of C++ handles file operations which are very much similar to console input and
output operations. It uses file streams as an interface between the programs and the files. The streams that
supply data to program is known as input stream while the stream that receives data from the program is
known as output stream.
In other words input stream extract or reads data from the file and the output stream inserts or
writes data to the file. The input operation involves the creation of an input stream and linking it with the
program and the input file. Similarly the output operation involves establishing an output stream and linking
it to the program and the output file.
Input Stream
Data
Input
Read Data
78 | P a g e
Q) Describe the various classes are available for file operations.
The I/O system of C++ contains a set of classes that defines the file handling methods.
These includes ifstream, ofstream and fstream. These classes are derived from fstreambase class
the corresponding iostream.h (header fiile) as shown in following figure. These classes are designed
to manage the disk files are declared in fstream.h (header file) and therefore we must include this
file in any program that uses files.
1) filebuf( ) : - Its purpose is to set the file buffers to read and write. It contains „openport‟ constant
and used in the „open( )‟ of file stream classes. Also it contains close( ) and open () as members.
2) fstreambase ( ) : - It provides operations common to the file streams. It serves as a base for
fstream, ofstream and ifstream classes. It contains open ( ) and close ( ) functions.
3) Ifstream:- It provides input operations and contains open ( ) with default input mode. It contains
functions such as get ( ), getline ( ), read ( ), seekg ( ) and tellg ( ) et c from ifstream class.
4) ofstream : - It provides output operations and contains open ( ) with default output mode. It
inherits functions such as put ( ), seekp ( ), tellp ( ) and write ( ) functions from ostream.
5) fstream :- It provides support for simultaneous input and output operations. It contains open ( )
with default input mode. It inherits all the functions from istream and ostream classes through
istream.
Q) What are classes in C++ for file stream operations? How do you open a file using open ( )
function and close file using close ( )?
79 | P a g e
Q) What are different file modes for open a file ?
The following table lists the file mode parameters and their meanings is used with open ( ).
Parameter Meaning
1) ios : : app Appends to end-of-file.
2) ios : : ate Goto end-of-file on opening.
3) ios : : binary Binary file.
4) ios: :in Open a file for reading only.
5) ios : : nocreate Open fails if the file does not exist.
6) ios : : noreplace Open fails if the file already exist.
7) ios : : out Open file for writing only.
8) ios : :trunk Delete contents of file if it exist.
80 | P a g e