You are on page 1of 32

Procedure oriented programming(POP):-In pop the problem is viewed as sequence

of things to done such as reading, calculating and printing. A number of functions are
written to accomplish these task. Primary focus is on functions.

Global data
Accessible by any function

Function A Function B

Local data Local data


Accessible only by function A Accessible only by function B

Relationship of data and functions in POP

Characteristics of POP are:-


1. Emphasis on doing things.
2. Large program is divided into functions to reduce the complexity of
program.
3. Most of functions share global data.
4. Data move openly around the system from function to function.
5. Functions can modify data from one form to another.
6. Employs top-down approach in program design.

Object oriented programming(OOP):- It overcome the drawbacks of POP. It treats


data as a critical element in the program development and does not allow it to flow
freely around the system.

Characteristics of OOP are:-


1. Emphasis on data rather then procedure.
2. Programs are divided into objects.
3. Functions that operate on data are tied together in the data structure(class).
4. Data is hidden and cannot be accessed by the external functions.
5. Objects may communicate with each other through functions.
6. Employs bottom-up approach in program design

Organization of data and functions in OOP


OOP allows decomposition of problem into a number of entities called objects
and then builds data and functions around these objects. The data of an object can be
accessed only by the functions associated with that object. However functions of one
object can access the functions of other objects.

1
Object A Object B
Data data
| |
functions functions
Object C
Functions
|
data

Basic concepts of object oriented programming are


1. object
2. class
3. data abstraction and encapsulation
4. inheritance
5. polymorphism
6. dynamic binding
7. message passing

1. Object:- objects are the basic run time entities in object oriented
programming. They are variables of a class. Any number of objects can be
created. Each object is associated with the data type class with which they
are created. They may represent a person, a place, a bank account etc.

Object: student
Data
Name
Marks
Functions
Total
Percentage
2. Class :- The entire set of data and code of an object can be made as user
defined data type is known as a class. Class is a collection of objects of
similar type.
Eg. Fruits, students, employee etc.

3. Data abstraction and encapsulation:- Abstraction refers to the act of


representing essential features without including the background details.
The wrapping of data and functions in a single unit is known as
encapsulation.

4. Inheritance:- inheritance is a process by which objects of one class acquire


the properties of objects of another class. It is a mechanism of deriving a
new class from old one. Old class is referred as base class and new class is
referred as derived class.

5. Polymorphism:- polymorphism is the ability to take more than one form.


An operation may show different behaviour at different instances. Operator

2
overloading , function overloading are the examples of polymorphism. It is
used in implementing inheritance.

6. Message passing:-In object oriented programming objects communicate


with one another by sending and receiving information. A message for an
object is a request for execution of a function, and therefore will invoke a
function in the receiving object that generates the desired result.

Ex.

Student.result(marks);
| | |
| | |
object message information

Benefits of object oriented programming:


1. Through inheritance redundant code can be eliminated and extend the use of
existing classes.
2. The principle of data hiding helps the programmer to build secure programs
that cannot invaded by code in other parts of the program.
3. It is possible to have more than one instances of an object to coexist without
any interference.
4. It is possible to partition the work in a project based on objects.
5. Object oriented systems can be easily upgraded from small to large system.
6. Software complexity can be easily managed.
7. Programs can be build from the standard working modules that communicate
with one another, rather than having to start writing code from scratch. This
leads to saving of development time and higher productivity.

Applications of object oriented programming


1. Simulation:-simulator is designed in oop. On which trainee engineer are
trained to operate the nuclear reactor and other equipments in nuclear power
plant.
2. Artificial intelligence and automation:-intelligent I/O interfaces can be
designed for supercomputers that directly communicate with human beings
in images, speech and natural languages.
3. Remote sensing application:-computer analysis of remotely sensed(via
satellite) earth resource data has many potential applications in agriculture,
forestry, geology etc.
4. Real time systems:- a real time operating system is used as a control device
in a dedicated application. Sensor brings data to the computer. The computer
must analyze the data and possibly adjust the controls to modify the sensor
inputs. Systems that control scientific experiments, medical imaging systems,
industrial control system, display system are real time system.
5. CAD/CAM:-CAD is used for designing and CAM is for manufacturing.
6. Parallel processing:-It performs the fast and efficient computations in various
fields for eg. medical, military etc.
3
Q1.1 What is procedure oriented programming? what are its main characteristics?
Q1.2 What is object oriented programming? what are its main characteristics?
Q1.3 What is object oriented programming? how it is different from procedure
oriented programming?
Q1.4 Explain the concept of object oriented programming.
Q1.5 What do you mean by dynamic binding(late binding)? How it is useful in
OOP?
Q1.7 What are the different applications of OOP?
Q1.8 What are the various benefits of the OOp?

Tokens:- the smallest individual unit in C++ is called tokens. Tokens are
Keywords ,identifiers ,constants ,strings ,operators.

Keywords:-The keywords are the reserved identifiers & its meaning known to the
compiler . They can’t be used as names for the program variables.
Keywords are
int, break, continue etc.

Identifiers :- identifiers refers to the names of variables, functions, classes, arrays etc.
created by the programmer.
Rules for identifiers are
1. only alphabetic characters, digits and underscores are permitted.
2. The name can’t start with digits.
3. upper case and lower case letters are distinct.
4. keywords can’t be used as identifier name.
5. there is no limit on the characters of the identifier.
6. all characters in the name are significant.

Constants:- constants refers to the fixed values that do not change during program
execution. constants are
Integer constant
Eg. 56
Floating point constant
Eg 45.78
Character constant
Eg. ‘F’
String constant
Eg. “I know C++ programming language.”

C++ data types classified into following categories


1. basic or built in data types
2. user defined data types
3. derived data types

4
Basic or built in data types:-The data types which are known to the compiler are
called built in data types.
Built in data types are
• Integer:- It accepts whole numbers only. It is denoted by int. Its takes 2 bytes to
store the number. It can be signed int , unsigned int.
Eg.
int a=23;

• Short integer:-It accepts whole numbers whose size is smaller then int. It takes 2
bytes to store the number. It can be short int, unsigned short int.
Eg.
short int s=1;
• Long int :- It accepts whole numbers whose size is bigger then int. It takes 4
bytes to store the number. It can be long int, unsigned long int.
Eg.
long int b=556789;
• Character:- It accepts a single character. It is denoted by char. It takes 1 byte to
store the number. It can be signed char, unsigned char
Eg.
char c=‘e’;
• Floating point:-It accepts fractional numbers. It is denoted by float. It takes 4 byte
to store the number.
Eg. float f=45.6;
• Double:-It accepts the fractional numbers larger then float. It takes 8 bytes to store
the number.
Eg. double d=2.4E+20;
• Long double:- It accepts the fractional numbers larger then double. It takes 10
bytes to store the number.
Eg. long double d=1.1E+4399;

User defined data types:-data types defined by the user as per program’s requirement
are called user defined data types.
User defined data types are
• Structure:- structure is a collection of variables of different data types. It is
denoted by keyword struct.
Eg.
struct
{
char name[20];
int rollno;
}

• Union:-Its members all occupy the same memory location. The size of the union
is the size of its largest member. It is defined by keyword union.
Eg.
Union student
{

5
int rollno;
double percentage;
}

• Class:- The entire set of data and code of an object can be made as user defined
data type is known as a class. Class is a collection of objects of similar type.
Eg. Fruits, students, employee etc.

• Enumerated data type:-in this data type names are associated to the numbers. It is
denoted by keyword enum.
Eg.
enum option{false,true};
option f; //f is option type

Derived data type


• Array :- is a set of elements of same data type.
Eg.
int student[10];

• Function:-it is a self defined block of statements. It perform a task assigned to it.


Eg.
int sum(int,int);

• Pointer:-pointer variable stores the address of the other variable.


int b;
int *ptr;
ptr=&b; // ptr store the address of b

• Reference:- A reference variable provides an alias(alternative name) for a


previously defined variable.
Eg.
int m;
int &x=m; //x is alias for m

Control structures:- control structures are the method to trace the flow of execution
of statements. It makes the program debugging easy.
Control structures are
1. Sequence structure
2. Selection structure
3. Loop structure

1. Sequence structure:-the instructions are executed one after the other in the
sequence in which they are specified in the program.

6
Step1
|
step2
|
step3
|

2. Selection structure:-selection structure employs a number of conditions which


lead to a selection of one out of several alternative module.
Selection structure are
I single alternative
if (condition)
{
Module A
}

II double alternative
if (condition)
{
Module A
}
Else
{
Module B
}

III multiple alternative


if (condition1)
{
Module A
else if (condition2)
{
Module B
}

else if (condition3 )
{
Module C
}
else
{
Module D
}

3. Loop structure:-a block of statements executed till condition is true.


for (initialization; condition; increment)
{
Module A
7
}

while(condition)
{
Module B
}

do
{
Module C
}while(condition);

Memory management operators:-


• new operator :- It is the operator which allocate memory dynamically at run
time. An object can be created by using new as and when required.
Eg
int *p=new int;
• delete operator:-is the operator which free memory dynamically at run time. An
object can be destroyed by using delete as and when required.
Eg
int *p=new int;
delete p;

Manipulators:- manipulators are operators that are used to manipulate the data
display. Manipulators are endl and setw
endl:- when endl is used in an output statement , causes a linefeed to be inserted. It has
the same effect as using newline character “\n”.
eg.
cout<<”good morning India”<<endl;

setw:- setw is used to specify a field width for printing the value of a variable.
eg.
cout<<setw(5)<<sum;

Q2.1 Explain the following terms


i token
ii identifier
iii keywords
iv constants
Q2.2 What are the different control structures are used in C++?
Q2.3 Explain inbuilt(basic) data types used in C++ with their size in bytes and give
one example of each.
Q2.4 Explain user defined data types used in C++ with one example of each.
Q2.5 Explain derived data types used in C++ with one example of each.
Q2.6 Explain various data types used in C++ in brief.
Q2.7 Explain with example different memory management operators in C++.
Q2.8 Explain with example different manipulators in C++.

8
Q3.1 What is a class. Give its general form and explain in brief.
Ans: class :- The entire set of data and code of an object can be made as user
defined data type is known as a class. Class is a collection of objects of similar
type.
General form of a class declaration is
class class_name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};
where
private, public are the visibility modes .
variables declared inside the class are known as the data members.
Functions declared inside the class are known as the member functions.

Q3.2 How is a member function of a class defined?


Ans: Member functions can be defined
• inside the class definition
• outside the class definition
Inside the class definition:-in this method the member function definition is
written inside the class definition. When function if defined inside the class , it is
treated as inline function.
Outside the class definition:-in this method the member function is declared
inside the class. And the definition of the member function is defined outside the
class.
Eg.

class student
{
int rollno;
int marks;
public:
void getdata( ); //function declaration
//member function definition inside the class
void putdata( )
{
cout<<”rollno:”<<rollno;
cout<<”\nmarks:”<<marks;
}
};
//member function definition outside the class
void student::getdata( )
{

9
cout<<”enter rollno and marks”;
cin>>rollno>>marks;
}

Q3.3 What are objects? How are they created?


Ans: Object:- objects are the basic run time entities in object oriented programming.
They are variables of a class. Any number of objects can be created. Each
object is associated with the data type class with which they are created. They
may represent a person, a place, a bank account etc.
eg.
class student
{
int rollno;
int marks;
public:
void getdata( );
void putdata( );
};
void main( )
{
student s1,s2 ; //objects are created
}

Q3.4 Can we use the same function name for a member function of a class and an
outside function in the same program file? If yes, how are they distinguished ?
If no, give reasons.
Ans: yes, we can use the same function name for a member function of a class and
an outside function in the same program file. A member function of a class is
accessed with help of its object. While the outside function is accessed as a
normal function without the help of an object. Its prototype is declared before
main( );
eg.
#include <iostream.h>
#include <conio.h>
void putdata();
class student
{
int rno;
int marks;
public:
void getdata()
{
cout<<"enter rno,marks";
cin>>rno>>marks;
}
void putdata()
{
cout<<rno<<endl;
cout<<marks;
}
};

10
void main()
{
student s;
s.getdata();
s.putdata();
putdata();
}
void putdata()
{
cout<<"rno"<<endl;
cout<<"marks";
}

Q3.5 What is a friend function? what are the characteristics of the friend function?
Ans: A function that is declared with the keyword friend is known as a friend
function. It is defined elsewhere in the program like a normal C++ function.
Characteristics of friend function
i) It is not in the scope of class to which it is declared as a friend.
ii) It has full access to the private and public members of the class.
iii) It can be invoked like a normal function without the help of any object.
iv) It has the objects as arguments
v) It can be declared in private or public part of the class.
vi) To access the members it has to use an object name and dot operator with each
member name.(eg. ob.x)

Q3.6 Describe the mechanism of accessing data members and member functions in
the following cases:
a. Inside the main program.
b. Inside a member function of same class.
c. Inside a member function of another class.
Ans: Accessing class members
a. inside the main function:-private members can’t be accessed inside the main
function. Public data members and member functions can be access by using an
object of the same class.
b. inside member function of the same class:-private and the public data member
and member function can be access directly by using the name of the member.
c. inside a member function of another class:-By making the member function of
one class as a friend function of another class private and public data member
and member functions can be accessed.

Q3.7 What is a friend function? What are the merits and demerits of using friend
functions.
Ans: A function that is declared with the keyword friend is known as a friend
function. It is defined elsewhere in the program like a normal C++ function.
Merits of friend function
i It has full access to the private and public members of the class.
ii It can be declared in private or public part of the class.

11
Demerits of friend function
i private data is available to friend function therefore data may not be secure.
ii It is not in the scope of class to which it is declared as a friend.

Q3.8 When do we declare a member of a class static ? what are the characteristics of
the static member?
Ans: Member of a class can be declared as static when the member is common to
the entire class. data members as well as member functions can be static.
Features of static data member
i It is initialized to zero when the first object of its class is created. No other
initialization is permitted.
ii Only one copy of that member is created for entire class and is shared by all
the objects of that class.
iii It is visible only within the class, but its lifetime is the entire progam.
Features of static member function
i A static function can have access to only other static members.
ii A static member function can be called using the class name.

Q4.1 What is constructor? Is it mandatory to use constructors in a class? How do we


invoke a constructor function?
Ans Constructor is a special member function whose task is to initialize the object
of its class when object is created. Name of the constructor is same as the
name of the class.
No, it is not mandatory to use constructors in a class.
Constructor can be invoked in two ways
i) By calling the constructor implicitly
ii) By calling the constructor explicitly
Eg.
class student
{
int a;
public:
student(int x) //constructor
{
a=x;
}
};
void main( )
{
student s1(12); //implicit call to constructor
student s2=student(30); //explicit call to constructor
}

Q4.2 List the features of the constructor functions.


12
Ans Features of constructor functions
i) They should be declared in public section.
ii) They are invoked automatically when objects are created.
iii) They do not have return type, not even void, and therefore, they can’t return
values.
iv) They can’t be inherited, though a derived class can call the base class
constructor.
v) They can have default argument.
vi) They can’t be virtual
vii) User can’t refer to their addresses.
viii) An object with constructor can’t be used as a member of a union.

Q4.3 What is parameterized constructor?


Ans:- The constructor that takes arguments is called a parameterized constructor.
These constructors are useful to initialize different values for different objects.
When objects are created.
Eg.
class item
{
int x,y;
public:
item(int m, int n)
{

x=m;
y=n;
}
};
void main( )
{
item ob1(10,20); //object 1 is created
item ob(30,40); //object2 is created
}

Q4.4 Can we have more then one constructors in a class? If yes, explain the need for
such a situation.
Ans:- Yes, we can have more then one constructor in a class. Such constructor is
called overloaded constructor.
Overloaded constructor is needed when more then one objects are created of
same class and the objects are with the different number of arguments.
Eg.
class item
{
int x,y;
public:
item ( ){ } //no argument constuctor
item(int c) //one argument constructor
13
{
x=c;
}
item(int m, int n) //two argument constructor
{

x=m;
y=n;
}
};
void main( )
{
item ob1; //no arg. Constructor is invoked
item ob2(10); //one arg. Constructor is invoked
item ob3(30,40); //two arg. Constructor is invoked
}

Q4.5 What do you mean by dynamic initialization of objects? Why do we need to do


this?
How is dynamic initialization of objects achieved?
Ans:- Allocation of memory to object at the time of their construction is known as
dynamic initialization of objects.
This enable the system to allocate the right amount of memory for each object
when the objects are not of the same size, thus resulting in the saving of
memory.
The dynamic initialization of the objects are achieved with the help of new
operator.
Eg.

char *name;
int length;
name=new char[length+1];

Q4.6 What is copy constructor? explain in brief with example.


Ans:- When a constructor is used to declare and initialize an object from another
object such constructor is called a copy constructor. A copy constructor takes a
reference to an object of the same class as itself as an argument.
Eg.
class cost
{
float item;
public:
cost( ) { } //no arg. constructor
cost(float c) // one arg. constructor
{
item=c;
}
14
cost(cost & ob1) // copy constructor
{
item=ob1.item
}
};
void main( )
{
cost ob1(40.5); //object ob1 is created
cost ob2(ob1); // copy constructor called
}

in above example object ob2 is created and initialized with the value of object
ob1.

Q4.7 What is destructor? List the features of destructor.


Ans:- Destructor is a member function which destroy the objects that have been
created by the constructor. Name of the destructor is same as the name of the
class. It is preceded by tilde .
Features of destructor
i) It is declared in public section.
ii) It never takes any argument.
iii) It does not return any value.
iv) It is invoked by the compiler at the end of program or function or
block to free the memory.
v) It can’t be virtual.
vi) User can’t refer to it’s address.
vii) It can’t be inherited.

Q5.1 What is operator overloading? Why it is necessary to overload an operator?


Ans:- Overloaded operators are those that have been redefined within
a C++ class using the keyword operator followed by an operator
symbol.
When an operator is thus overloaded, the resulting symbol is
called the operator function name.
All operators can be overloaded except for these:
. .* :: ?:
and the preprocessor symbols # and ##.
With the exception of the assignment function operator =(), all
overloaded operators are inherited by any classes derived from
the class they are defined in.
By overloading the operator we can perform the various
operations such as + - etc. on the user defined data type
with the same syntax that is applied to the basic data type.

Q5.2 What is an operator function? Describe the syntax of an operator function.


Ans:- Overloaded operators are those that have been redefined within a c++ class.
This is done with the help of special function, called operator function.

15
The general form of operator function is:

return type classname :: operator op(op-arglist)


{
function body //task defined
}

where
return type is the type of value returned by the specified operation.
op is the operator being overloaded.
operator is the keyword
operator op is the function name.
op-arglist is the list of arguments.

Eg.
Vector operator+(vector) // vector addtion

Q5.3 What are the rules for overloading operators?


Ans:- List of rules for overloading operators are
1. Only existing operators can be overloaded. New operators cannot be created.
2. The overloading operator must have at least one operand that is of user defined
type.
3. We cannot change the basic meaning of an operator.
4. Overloaded operator follow the syntax rules of the original operators.
5. Unary operators overloaded by means of a member function, take no explicit
arguments , but those overloaded by means of a friend function, take one
explicit argument (object of relevant class).
6. Binary operators overloaded by means of a member function, take one explicit
arguments , but those overloaded by means of a friend function, take two
explicit arguments (object of relevant class).

Q5.4 How many arguments are required in the definition of an overloaded unary
operator?
Ans:- When unary operator is overloaded by using operator function as a friend
function one argument is required.
Eg.
void friend operator-(sign); //sign is a class name
When unary operator is overloaded by using operator function as a member
function no argument is required. This is because the object used to invoke the
member function is passed implicitly and therefore available for the member
function.
Eg.
void operator-( ) //overload unary operator

Q5.5 Differentiate operator overloading using member function and friend function.

16
Ans:- operator overloading using operator overloading using
member function friend function
1. for unary operator overloading 1. for unary operator overloading
no explicit argument is required. One explicit argument is required.
2. for binary operator overloading 2. for unary operator overloading
one explicit argument is required. two explicit argument are
required.
3. member function can overload 3. friend function cannot overload
following operators following operators
= assignment operator = assignment operator
( ) function call operator ( ) function call operator
[ ] subscripting operator [ ] subscripting operator
-> class member operator -> class member operator

Q5.6 List the operators which can’t be overloaded.


Ans:- Operators that can’t be overloaded are
Sizeof size of operator
. member operator
.* pointer to member operator
:: Scope resolution operator
?: conditional operator

Q5.8 What are the different types of data type conversion are present ? Explain in
brief.
Ans:- Three types of data conversion between uncompatible types are
i) Conversion from basic type to class type
ii) Conversion from class type to basic type
iii) Conversion from one class type to another class type

i) Conversion from basic type to class type:- The constructors used for the type
conversion take a single argument whose type is to be converted.
Eg.
Class time
{
int hrs;
int min;
public:
time( ){ }
time(int t)
{
hrs=t/60;
min=t%60;
}
};
void main( )
{
time ob; //object is created
17
int t=65;
ob=t; // int to class type
}

ii) Conversion from class to basic type:-Overloaded casting operator function is


used.It should satisfy the following condition
It must be a class member. It must not specify a return type. It must not have any
argument.
Eg.
//typecast conversion from user defined type to basic type
#include <iostream.h>
#include <conio.h>

class time
{
int hr;
int sec;
public:
time(){}
time(int h, int s)
{

hr=h;
sec=s;
}
operator int() //conversion function
{ //convert time to seconds
int s1=hr*60;
s1 +=sec;
return s1;
}

};
void main()
{ clrscr();
time t1(1,30); //calling 2 arg constructor
/*uses conversion function to convert time to
seconds*/
int s=t1;

cout<<"time in seconds="<<s;
getch();
}

iii) Conversion from one class type to another class type:-Conversion between
objects of different classes can be carried out by either a constructor or a
conversion function.
/*conversion between objects of different classes
converts polar to rec using routine in rec(destination)*/
#include<iostream.h>
#include <math.h>
#include<conio.h>
class polar
{

18
private:
double radius;
double angle;
public:
polar()
{
radius=0.0;
angle=0.0;
}
polar(double r,double a)
{
radius=r;
angle=a;
}
void display()
{
cout<<"("<<radius<<","<<angle<<")";
}
double getr()
{
return radius;
}
double geta()
{
return angle;
}
};
class rec
{
private:
double xco;
double yco;
public:
rec()
{
xco=0.0;
yco=0.0;
}
rec(double x, double y)
{
xco=x;
yco=y;
}
rec(polar p)
{
float r=p.getr();
float a=p.geta();
xco=r*cos(a);
yco=r*sin(a);
}
void display()
{
cout<<"("<<xco<<","<<yco<<")";
}
};
void main()
{
clrscr();

19
rec recob;
polar polob(10.0,0.785398);
recob=polob;
cout<<"\npol=";
polob.display();
cout<<"\nrec=";
recob.display();
getch();
}

Q6.1 What does inheritance mean in C++? What are different forms of inheritance?
Give an example of each.
Ans:- Inheritance is a process by which objects of one class acquire the properties of
objects of another class. It is a mechanism of deriving a new class from old
one. Old class is referred as base class and new class is referred as derived
class.
Different forms of inheritance are
1. Single inheritance
2. Multiple inheritance
3. Hierarchical inheritance
4. Multilevel inheritance
5. Hybrid inheritance
1. Single inheritance:-A derived class with only one base class is called single
inheritance.

Eg.
class A
{
members of class A;
}
class B: public A
{
members of class B;
}

2. multiple inheritance:- A derived class with several base classes is called


multiple inheritance.

20
Multiple inheritance

class A
{
members of class A;
}
class B
{
members of class B;
}
class C : public B, public C
{
members of class C;
}

3. Hierarchical inheritance : When more than one classes are derived from a
single base class, it is called hierarchical inheritance.

Hierarchical inheritance

Eg.
class A
{
members of class A;
}
class B : public A
{
members of class B;
}
21
class C : public A
{
members of class C;
}

4. Multilevel inheritance:-The mechanism of deriving a class from another


derived class is known as multilevel inheritance.

Multilevel inheritance

Eg.
class A
{
members of class A;
}
class B : public A
{
members of class B;
}
class C : public B
{
members of class C;
}

5. Hybrid inheritance:-When a class is derived from the combination of more


than one inheritance, it is called hybrid inheritance.

Hybrid inheritance
22
Eg.

class A
{
members of class A;
}
class B : public A
{
members of class B;
}
class C
{
members of class C;
}

class D : public B, public C


{
members of class D;
}

Q6.2 Describe the syntax of the single inheritance in C++?


Ans:- syntax for single inheritance
class derived-class-name : visibility-mode base-class-name
{

members of derived classes;


}

where
colon indicates that the derived –class-name is derived from the base-class-
name.
visibility mode specifies whether the features of the base class are privately
derived or publicly derived. It is optional by default visibility mode is private.

Q6.3 When do we use the protected visibility specifier to a class member?


Ans:- We use the protected visibility specifier to a class member when we want the
class member should be accessible to the member functions within its class and
any class immediately derived from it.

23
Q6.5 What is virtual base class. When do we make a class virtual?
Ans:- When a derived class inherit the same characteristics through various paths,
than there is a duplication of characteristics. This can be avoided by making
the common base class as virtual base class. When a class is made a virtual
base class C++ takes necessary care to see that only one copy of that class is
inherited, regardless of how many inheritance paths exists between the virtual
base class and a derived class.
Eg.

Student

As virtual base class as virtual base class

Test sports

Result

Virtual base class

In above eg. result class inheriting same characteristics twice through test class
and sports class. this duplication can be avoided by making common base class
as a virtual base class.

Q7.1 What does polymorphism mean in C++ language?


Ans:- polymorphism is the ability to take more than one form. An operation may
show different behaviour at different instances.
Polymorphism types
iv) compile time polymorphism
a) function overloading
b) operator overloading
v) run time polymorphism
a) virtual functions

Q7.2 How is polymorphism achieved at (i) compile time (ii) run time?
Ans:-
i) compile time polymorphism can be achieved by function overloading and
operator overloading. The overloaded functions are selected for processing by
matching arguments, both type and number . This information is known to the
compiler at compile time and therefore compiler is able to select appropriate

24
function at the compile time itself . This is called early binding or compile time
polymorphism.
Eg.
void box(int);
void box(int, int, int);
in above eg. box is a overloaded function.
ii) Run time polymorphism can be achieved by virtual functions. When the
function name is same in both the base and derived classes, the function in
base class is declared as a virtual function. At run time when it is known which
class object is under consideration the appropriate version of function is
invoked. Since the function is linked with a particular class munch later after
compilation, this process is known as late binding or run time polymorphism.

Eg.
class base
{
int x;
public:
virtual void show(){ }
};
class derived
{
int y;
public:
void show( ) { }
};
void main( )
{
base b;
derived d;
base *ptr;
ptr=&b;
ptr-> show( ); //call base class version
ptr=&d;
ptr->show( ); //call derived class version
}

Q7.5 What does this pointer point to? What are the application of this pointer?
Ans:- this pointer points to the object which invokes a member function.
For eg. A.max() will set pointer this to the address of the object A.
Application of this pointer
i) this pointer is automatically passed to a member function when it is called.It
acts as implicit argument to all the member functions.
Eg.
Class XYZ
{
int a;
};
25
private variable a can be used directly inside a member function, like
a=123;
ii) When a binary operator is overloaded using member function, the first
argument is passed implicitly using this pointer.
iii) this pointer is used to return the object it points to.
Eg.
return *this;

inside a member function will return the object that invoked the function.

Q8.1 What are input and output streams?


Ans:- The stream that supplies data to the program is known as input stream. And the
stream that receive data from the program is known as output stream. In other
words the input stream extracts(or read) data from the file and the output
stream inserts(or write) data to the file.

Input stream

Read data input data

Disk files program

Write data data output

Output stream

File input and output streams


Q8.2 What are the steps involved in using a file in C++ program?
Ans:- i) suitable name for the file:-file name is a string of characters. It contains
two parts primary name and extension.
Eg.
Input.dat
ii) Data type and structure :- which type of data wants to read from or
write in the file int, float, char etc.
iii) Purpose:-weather we want to read data from the file or write data to it.
iv) opening method :- a file can be open in two ways using constructor
function and member function open() of the class.

Q8.3 Describe the various classes available for file operations?


Ans:- The I/O system of C++ contains a set of classes that define the file handling
methods. These include ifstream, ofstream and fstream classes. These classes
are derived from fstreambase class. These classes are designed to manage the
disk files, are declared in fstream.h file.

26
Ifstream provides input operations. Contains
open( ),get(),getline(),read(),seekg() and tellg() functions.
Ofstream provides output operations. Contains open( ),put(), seekp(), tellp(),
and write() functions.
Fstream() provides support for simultaneous input and output
operations.Contains open() with default input mode. Inherits all the functions
from istream and ostream classes.

Q8.4 In how many ways a file can be open? Explain.


Ans:- A file can be open in two ways
a. using the constructor function of the class.
b. Using the member function open() of the class.
i) using the constructor function of the class:- this method is useful when
we use only one file in the stream.
Steps to open a file using a constructor are
a) Create a file stream object to manage the stream using the
appropriate class. Class ofstream for output stream and class
ifstream for input stream.
b) Initialize the file object with the desired filename.
Eg.
ofstream outob(“results”) //output only
This creates outob as an ofstream object that manages the output
stream. It opens the file results and attaches it to the output stream
outob.

ii) Using member function open() of the class:- this method is useful to
open multiple files that use the same stream object.
Eg.
ofstream outob; //create stream for output
outob.open(“database1”) //connect stream to database1 file
outob.close(); //disconnect stream from database1
outob.open(“database2”) //connect stream to database2
outob.close(); //disconnect stream from database2

Q8.5 What is the difference between opening a file with constructor function and
opening a file with open() function? When is one method preferred over the
other?
Ans:- ans as above 8.4

Q8.6 What is file mode? Describe the various file mode options available?
Ans:- The second argument in the open( ) function specify the purpose of opening a
file for reading or writing, that argument is called file mode parameter.
General form of the function open() with two arguments is
Stream-object.open(“filename”,”mode);
Eg.
fstream ob1; //create object of fstream
ob1.open(“result”,”ios::app”) //open file in append mode
27
Various file mode parameter
Parameter Meaning
ios : : app Append to end of file
ios : : ate Go to end of file on opening
ios : : binary Binary file
ios : : in Open file for reading only
ios : : nocreate Open fails if the file does not
exist
ios : : noreplace Open files if the file already exist
ios : : out Open file for writing only
ios : : trunc Delete the contents of the file if it
exists

Q8.7 How many file objects would you need to create to manage the following
situations?
i) To process four files sequentially
ii) To merge two sorted files into a third file.
Ans:- i) To process four files sequentially : one stream object is required . open
file1 and attach it to stream object . As soon as the file1 work is over close
file1. Open file2 and attach it to same stream object with the file2, when
its work is over close it. Similarly work with file3 and file4 sequentially.
Eg.
Ofstream ob; // create stream for output
ob.open(“file1”); //connect stream to file1
……….
ob.close(); //close file1
ob.open(“file2); //connect stream to file2
………..
ob.close(); //close file2
………..

ii ) To merge two sorted files into a third file:- We need three stream
objects. Two separate input stream objects for handling the two input files
and one output stream object for handling the output file.
ifstream ob1,ob2; //create two input stream
ofstream ob3; //create one output stream
ob1.open(“infile1”);
ob2.open(“infile2”);
ob3.open(“outfile3”)

Q8.8 What do you mean by saving data in binary form in file?what are the
advantages of saving data in binary form?
Ans:- Saving data in binary form means values are stored in disk file in the same
format in which they are stored in the internal memory.
The binary input and output functions has the form
infile.read((char *) & v, sizeof(v));
28
outfile.wirte((char *) & v, sizeof(v));
The first argument is the address of variable v,
Length of that variable in bytes.
Advantages
i) The binary format is more accurate for storing data as it is stored in the
exact internal representation.
ii) There are no conversions while saving the data and therefore saving is
much faster.

Q8.9 Describe the various approaches by which we can detect the end of file
condition successfully.
Ans:-
Q8.10 What are command line arguments?
Ans:- File names supplied as arguments to main() function at the time of invoking
the program. These arguments are known as command line arguments.
Eg.
c>exam data results
where exam is name of file containing program
data and results are the filenames passed to the program as command line
arguments.

The main() function can take two arguments


Main(int argc, char * argv[])
Where argc represents the no. of arguments in command line. argv is array of pointers
to strings which points to command line arguments
in above example argc=3
argv[0]--- exam
argv[1]----data
argv[2]----results

Q8.12 Explain in brief the different functions for manipulation of file pointers
Ans:- Functions for manipulation of file pointers are
i) seekg() :- moves get pointer(input) to a specified location.
ii) seekp() :- moves put pointer(output) to a specified location.
iii) tellg() :- gives the current position of the get pointer.
iv) Tellp() :- gives the current position of put pointer.

Q8.13 What are the functions used for performing I/O operations on files?
Ans:- Funcitons for performing I/O operations on files are
i) get() :- reads a single character from associated stream.
ii) put() :- writes a single character to associated stream.
iii) read() :-reads a block of binary data from associated stream.
iv) wirte() :-writes a block of binary data to associated stream.

29
NOTES ON DATA STRUCTURE

30
Q1.6 How are data and functions are organized in OOP?

Q5.9 What is conversion function? How is it created? Explain its syntax.


Ans:-

Q5.9 When is a friend function compulsory ? Give an example.


Q5.10 We have two classes X and Y .If a is the object of class X and b is the object of
class Y and we want to say a=b; what type of conversion routine should be
used and where?
Q5.7 A friend function can’t be used to overload the assignment operator = . Explain
why?

Q6.3 We know that a private member of a base class is not inheritable. Is it anyway
possible for the objects of a derived class to access the private members of the
base class? If yes how? Remember the base class can’t be modified.

Q8.11 Describe random access of file?


Ans:-

Q7.3 Discuss the different ways by which we can access public member functions of
an object.
Q7.4 Explain, with an example, how you would create space for an array of objects
using pointers.

Q6.6 What is an abstract class?

Q6.7 In what order are the class constructors called when a derived class object is
created?
Q6.8 Class D is derived from class B. The class d does not contain any data
members of its own. Does the class D require constructors? If yes, why?

Q7.6 What is a virtual function? Why do we need virtual functions?

Q7.7 When do we make a virtual function pure? What are the implications of
making a function a pure virtual function?

31
32

You might also like