Biyani's Think Tank
Concept based notes
Object Oriented Technology
Using C++
(M.Sc I.T 2
ndSem)
Mr. Dhanesh Gupta
LecturerDeptt. of Information Technology Biyani Girls College, Jaipur
Published by :
Think Tanks
Biyani Group of Colleges
Concept & Copyright :
Biyani Shikshan Samiti
Sector-3, Vidhyadhar Nagar, Jaipur-302 023 (Rajasthan)
Ph : 0141-2338371, 2338591-95 Fax : 0141-2338007 E-mail : [email protected]
Website :www.gurukpo.com; www.biyanicolleges.org
First Edition :
Leaser Type Setted by :
Biyani College Printing Department
While every effort is taken to avoid errors or omissions in this Publication, any mistake or omission that may have crept in is not intentional. It may be taken note of that neither the publisher nor the author will be responsible for any damage or loss of any kind arising to anyone in any manner on account of such errors and omissions.
Preface
I
am glad to present this book, especially designed to serve the needs of the students. The book has been written keeping in mind the general weakness in understanding the fundamental concepts of the topics. The book is self-explanatory and adopts the “Teach Yourself” style. It is based on question-answer pattern. The language of book is quite easy and understandable based on scientific approach.Any further improvement in the contents of the book by making corrections, omission and inclusion is keen to be achieved based on suggestions from the readers for which the author shall be obliged.
I acknowledge special thanks to Mr. Rajeev Biyani, Chairman & Dr. Sanjay Biyani, Director (Acad.) Biyani Group of Colleges, who are the backbones and main concept provider and also have been constant source of motivation throughout this Endeavour. They played an active role in coordinating the various stages of this Endeavour and spearheaded the publishing work.
I look forward to receiving valuable suggestions from professors of various educational institutions, other faculty members and students for improvement of the quality of the book. The reader may feel free to send in their comments and suggestions to the under mentioned address.
Author
Syllabus
M.Sc I.T 2
ndSem.
Content
S.No. Name of Topic Page No.
1. Object-oriented Language
2. Class and Object
3. Polymorphism
4. Pointers and File Handling
5. Program 6 Keywords
7 Objective Questions
Chapter -1
Object-Oriented Programming
Q.1. What is OOP? Explain Characteristics of an Object-oriented Language. Ans.: OOP stands for Object-Oriented Programming. Object oriented
programming is combining the data and function in to a single unit , called object. The data of the object can be accessed by function associated with the object only . the function of one object can‟t access the data of other object.
Characteristics of an Object-oriented Language. 1) Class
Classes are the central feature of object-oriented programming and are often called user-defined types. A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.
2) Object
An object is an entity that has state, behavior and identity. A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types.
3) Encapsulation
Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding.
4) Data Abstraction
Data abstraction refers to, providing only essential information to the outside word and hiding their background details ie. to represent the needed information in program without presenting the details. Data abstraction is a programming (and design) technique that relies on the separation of interface and implementation.
Example of a TV which you can turn on and off, change the channel, adjust the volume, and add external components such as
speakers, VCRs, and DVD players BUT you do not know it's internal detail that is, you do not know how it receives signals over the air or through a cable, how it translates them, and finally displays them on the screen.
Thus we can say, a television clearly separates its internal implementation from its external interface and you can play with its interfaces like the power button, channel changer, and volume control without having zero knowledge of its internals.
5) Inheritance
One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.
6) Polymorphism
The word polymorphism is derived from two Greek words Poly which means many and morphos which means forms. So, polymorphism means the ability to take many forms.
Polymorphism can be defined as the ability to use the same name for two or more related but technically different tasks.
Overloading
An overloaded declaration is a declaration that had been declared with the same name as a previously declared declaration in the same scope, except that both declarations have different arguments and obviously different definition (implementation).
When we call an overloaded function or operator, the compiler determines the most appropriate definition to use by comparing the argument types you used to call the function or operator with the parameter types specified in the definitions. The process of selecting the
most appropriate overloaded function or operator is called overload
resolution.
7) Dynamic Binding
Binding refers to the linking of a function call to the code of function to be executed in response to the function call. Binding is of two types.
Static or early binding
Binding refers to the linking of a function call to the code of function to be executed in response to the function call is made at the compile time.
Dynamic or late binding
Dynamic Binding refers to linking a procedure call to the code that will be executed only at run time. The code associated with the procedure in not known until the program is executed, which is also known as late binding.
8) Message passing
Message Passing is nothing but sending and receiving of information by the objects. So this helps in building systems that simulate real life. Following are the basic steps in message passing.
Creating classes that define objects and its behavior. Creating objects from class definitions
Establishing communication among objects
In OOPs, Message Passing involves specifying the name of objects, the name of the function, and the information to be sent.
Q2 What are the differences between procedural languages and object oriented languages?
Ans
Procedure Oriented
Programming Object Oriented Programming Divided Into In POP, program is divided into
small parts called functions.
In OOP, program is divided into parts called objects.
Importance
In POP,Importance is not given to data but to functions as well as sequence of actions to be done.
In OOP, Importance is given to the data rather than procedures or functions because it works as a real world.
Approach POP follows Top Down
approach. approach. OOP follows Bottom Up
Specifiers specifier. named Public, Private, Protected, etc.
Data Moving from function to function in the In POP, Data can move freely system.
In OOP, objects can move and communicate with each other through member functions.
Expansion To add new data and function
in POP is not so easy.
OOP provides an easy way to add new data and function.
Data Access
In POP, Most function uses Global data for sharing that can be accessed freely from function to function in the system.
In OOP, data can not move easily from function to function,it can be kept public or private so we can control the access of data.
Data Hiding way for hiding data so it is less POP does not have any proper secure.
OOP provides Data Hiding so provides more security.
Overloading In POP, Overloading is not
possible.
In OOP, overloading is possible in the form of Function Overloading and Operator Overloading.
Examples Example of POP are : C, VB,
FORTRAN, Pascal. JAVA, VB.NET, C#.NET. Example of OOP are : C++,
Q.3. What are advantages Object-oriented Language. Ans The major advantages of OOPs are:
1. Simplicity:
Software objects model real world objects, so the complexity is reduced and the program structure is very clear.
2. Modularity:
Each object forms a separate entity whose internal workings are decoupled from other parts of the system.
3. Modifiability:
It is easy to make minor changes in the data representation or the procedures in an OO program. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.
Adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.
5. Maintainability:
Objects can be maintained separately, making locating and fixing problems easier.
6. Re-usability:
Objects can be reused in different programs.
Q4 What is the basic structure of C++? Ans Basic Structure of C++ program:
#include directive Global Declarations return-type main() { Statements } Include Directive:
The "#include" directive is used to include the files specified inside the "<>" brackets. Mostly standard files or header files of C++ are included using this directive like iostream.h, math.h etc.
Global Declarations:
The variables and other elements that need to be used all over the program or rather globally should be declared after the include directive.
main() Function:
The main function is executed first in a C++ program. If a main() is supposed to return a integer value then the return type should be specified as "int main()". If no value is returned simply use the return-type as "void".
The statements used inside the "main()" function can include the functions, classes used in C++ along with other statements.
For Example: #include <iostream.h> void main() { cout << "Welcome"; }
Q 4. How do we define a character set?
Ans Any alphabet ,digit or symbols to represent information is called
Character . The characters are grouped into following categories: 1 Letters
2 Digits
3 Special characters 4 White spaces
The following are the valid alphabets, numbers and special symbols permitted in C.
Digits: From 0 to 9
Letters: From a to z, A to Z. Special characters : , . ? „ “ / \
White space: Blank Spaces , Tab , New Line.
Q5 What are Identifiers?
Ans Identifiers" are the names that we supply for variables, types, functions,
and labels in our program. Identifier names must differ in spelling and case from any keywords. We cannot use keywords (either C or Microsoft) as identifiers; they are reserved for special use. We create an identifier by specifying it in the declaration of a variable, type, or function.
Q6 Define Variables.
Ans A variable is a name given to the memory location for holding data. The name of the memory location i.e. the variable name, remain fixed during execution of the program but the data stored in that location may change from time to time.
Eg. Marks1 , Marks2, abc , a , ab_1 ,
Rules for writing variable names
1. The first character of variable name must be an alphabetic. 2. Blank spaces are not allowed in a variable name.
3. Special characters such as arithmetic operators, #,^ can not be used in a variable.
4. Reserved words(Keywords) cannot be used as variable names.
5. The maximum length of a variable name depends upon the compiler (8). 6. A variable name declared for one data type cannot be used to declare
Q7 What do you mean by constants?
Ans Constant is fixed value which can not be changed by the program during the execution.
Eg. A=5 in this 5 is constant.
Q 8. How many types of constants ?
Ans. There are mainly three types of constants namely: integer, real and
character constants.
1. Integer Constants:
(i) Decimal Integer Constant: 0 to 9
E.g: 49, 58, -62, … (40000 cannot come bcoz it is > 32767)
(ii) Octal Integer Constant: 0 to 7
Add “0” before the value. Eg.: 045, 056, 067
(iii) Hexadecimal Integer:0 to 9 and A to F Add 0x before the value
E.g: 0x42, 0x56, 0x67
2. Real Constants:
The real or floating point constants are in two forms namely fractional form and the exponential form.
A real constant in fractional form must have a digit with a decimal part.Ex 456.78
In exponential form, the real constant is represented as two parts. The part lying before the „e‟ is the „mantissa‟, and the one following „e‟ is the „exponent‟.
Ex: +3.2e-4, 4.1e8, -0.2e+4, -3.2e-4
3. Character Constants
A character constant is an alphabet, a single digit or a single special symbol enclosed within inverted commas. Ex: ‟B‟, ‟l‟, ‟#‟
Q 9. What are key words?
A.ns They are the reserved words that cannot be used for naming a variable.
They perform fix tasks.
Q10 Discuss various operator in C++.
Ans An operator is a symbol that operates on a certain data type and produces
the output as the result of the operation.
Eg. expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator.
Category of operators
Unary Operators:-A unary operator is an operator, which operates on one operand.
Binary:-A binary operator is an operator, which operates on two operands Ternary:-A ternary operator is an operator, which operates on three operands.
C contains the following operator groups 1 Arithmetic Operator
The arithmetic operator is a binary operator, which requires two operands to perform its operation of arithmetic. Following are the arithmetic operators that are available.
Operator Description Eg.
+ Addition a+b
- Subtraction a-b
/ Division a/b
* Multiplication a*b
% Modulo or remainder a%b
2 Relational Operators
Relational operators compare between two operands and return in terms of true or false i.e. 1 or 0. In C++ and many other languages a true value is denoted by the integer 1 and a false value is denoted by the integer 0. Relational operators are used in conjunction with logical operators and conditional & looping statements.
< Less than > Greater than
<= Less than or equal to >= Greater than or equal to != Not equal to
3 Logical Operators
A logical operator is used to compare or evaluate logical and relational expressions. There are three logical operators available in the C++ language.
&& Logical AND || Logical OR ! Logical NOT
4 Assignment operator
An assignment operator (=) is used to assign a constant or a value of one variable to another. Example: a = 5; b = a; rate = 10.5 net = (a/b) * 100;
* There is always difference between the equality operator (==) and the assignment operator (=).
5 Conditional or Ternary Operator
A conditional operator checks for an expression, which returns either a true or a false value. If the condition evaluated is true, it returns the value of the true section of the operator, otherwise it returns the value of the false section of the operator.
Its general structure is as follows:
Expression1 ? expression 2 (True Section): expression3 (False Section) Example:
a=3,b=5,c;
c = (a>b) ? a+b : b-a;
The variable c will have the value 2, because when the expression (a>b) is checked, it is evaluated as false. Now because the evaluation is false, the expression b-a is executed and the result is returned to c using the assignment operator.
6 Bitwise Operators:
These are used to perform bitwise operations such as testing the bits , shifting the bits to left or right , one‟s compliment of bits. This operator can be apply on only int and char data type.
| Inclusive OR ^ Exclusive OR << Shift Left >> Shift Right ~ One's compliment ~A = 1100 0011
7 Increment and Decrement Operators
These operators are unary operators .
The increment and decrement operators are very useful in C++ language. They are extensively used in for and while loops. The syntax of these operators is given below.
++ --
8 Comma operator ( , ):-
The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered.
Q11 What are the ways to comment statement in C? Ans Comments are non executable statement
Most of C++ will support two types of comments: // Comment text goes here ( in line)
Q.12 Explain control structures available in C++. Ans C++ provides two styles of flow control:
Branching Looping
Branching or Decision :
Branching or Decision is so called because the program chooses to follow one branch or another.
if statement
This is the most simple form of the branching statements.It takes an expression in parenthesis and an statement or block of statements. if the
expression is true then the statement or block of statements gets executed otherwise these statements are skipped.
Syntex:- if with single statement if (expression)
statement;
Syntex:- if with block statement if (expression)
{
Block of statements; }
or
Syntex:- if with else statement if (expression) { Block of statements; } else { Block of statements; } Or
Syntex:- if with else if statement if (expression) { Block of statements; } else if(expression) { Block of statements; } else { Block of statements;
}
switch statement:
The switch statement is much like a nested if .. else statement. Its mostly a matter of preference which you use, switch statement can be slightly more efficient and easier to read.
switch( expression ) { case expression1: statements1; case expression2: statements2; case c-expression3: statements3; default : statements4; } Use of break
Use If a condition is met in switch case then execution continues on into the next case clause also if it is not explicitly specified that the execution should exit the switch statement. This is achieved by using
break keyword. Looping
Loops provide a way to repeat commands and control how many times they are repeated. C++ provides a number of looping way.
while loop
The most basic loop in C++ is the while loop. Like an If statement, if the test condition is true, the statements get executed. The difference is that after the statements have been executed, the test condition is checked again. If it is still true the statements get executed again.This cycle repeats until the test condition evaluates to false.
syntax while ( expression ) { Single statement or Block of statements;
}
for loop
for loop is similar to while, it's just written differently. for statements are often used to proccess lists such a range of numbers:
syntax:
for( expression1; expression2; expression3) {
Single statement or
Block of statements; }
In the above syntax:
expression1 - Initialisese variables.
expression2 - Condtional expression, as long as this condition is true, loop will keep executing.
expression3 - expression3 is the modifier which may be simple increment of a variable.
do...while loop
do ... while is just like a while loop except that the test condition is checked at the end of the loop rather than the start. This has the effect that the content of the loop are always executed at least once.
syntax do { Single statement or Block of statements; }while(expression);
break and continue statements
C provides two commands to control the loop: break -- exit form loop or switch.
continue -- skip 1 iteration of loop. #include
main() {
int i; int j = 10; for( i = 0; i <= j; i ++ ) { if( i == 5 ) { continue; } cout<<”Hello” <<i<<endl; } } Hello 0 Hello 1 Hello 2 Hello 3 Hello 4 Hello 6 Hello 7 Hello 8 Hello 9 Hello 10
The goto statement (unconditional branching)
goto allows to make an absolute jump to another point in the program. We should use this feature with caution since its execution causes an unconditional jump ignoring any type of nesting limitations.
The destination point is identified by a label, which is then used as an argument for the goto statement. A label is made of a valid identifier followed by a colon (:).
goto loop example
#include <stdio.h> int main () { int n=10; loop: cout<< n; n--;
if (n>0) goto loop; cout<< "FIRE”; } 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE! exit function
exit is a function defined in the cstdlib library.
The purpose of exit is to terminate the current program with a specific exit code. Its prototype is:
exit()
Q13 What is a Function?
Ans The function is a self contained block of statements which performs a task
of a same kind. C++ program does not execute the functions directly. It is required to invoke or call that functions. When a function is called in a program then program control goes to the function body. Then, it executes the statements. We call function whenever we want to process that functions statements i.e. more than 1 times. Any c++ program contains at least one function. Function is used to avoids rewriting the same code over and over.
The following is its format:
type name ( parameter1, parameter2, ...) { statements } where:
• type is the data type specifier of the data returned by the function. • name is the identifier by which it will be possible to call the function.
• parameters (as many as needed): Each parameter consists of a data type specifier followed by an identifier.
• statements is the function's body. It is a block of statements surrounded by braces { }. Eg. void add() { int a, b, c; clrscr();
cout<<\n<<" Enter Any 2 Numbers : "; cin>>&a>>&b;
c = a + b; cout<<\n<<” Addition is :”<<c); } void main() { void add(); add(); getch(); }
Q14 What are the types of functions ? Ans There are 2(two) types of functions as:
1. Built in Functions 2. User Defined Functions
1. Built in Functions :
These functions are also called as 'library functions'. These functions are provided by system. These functions are stored in library files. e.g.
clrscr() strcpy()
2 User Defined Functions :
The functions which are created by user for program are known as 'User defined functions'.
void add() {
int a, b, c; clrscr();
cout<<\n<<" Enter Any 2 Numbers : "; cin>>&a>>&b; c = a + b; cout<<\n<<” Addition is :”<<c); } void main() { void add(); add(); getch();
}
Q15. Define arrays.
Ans. A collection of variables which are all of the same type. It is a data structure, which provides the facility to store a collection of data of same type under single variable name. Just like the ordinary variable, the array should also be declared properly. The declaration of array includes the type of array that is the type of value we are going to store in it, the array name and maximum number of elements.
Examples:
short val[ 200 ]; //declaration val[ 12 ] = 5; //assignment
Q16. How is Array declared? Ans Declaration & Data Types
Arrays have the same data types as variables, i.e., short, long, float etc.They are similar to variables: they can either be declared global or local.They are declared by the given syntax:
Datatype array_name[dimensions]={element1,element2,….,element}
Q.17 Explain String.
Ans A group of characters stored in a character array. A string in C is a
sequence of zero or more characters followed by a NULL '\0' character: String constants have double quote marks around them,. Alternatively, we assign a string constant to a char array - either with no size specified, or you can specify a size, but don't forget to leave a space for the null character!.
Eg. char string_2[] = "Hello";
char string_3[6] = "Hello";
Q18 Explain structure and union in c++.
Ans. Structures in C++ is a collection of variables. Structures in C++ can be declared even without the keyword "struct". By default all the members of a structure are "public", even "private" members can also be declared in a function.
Syntax:
struct struct-type-name{
type name1: length; type name2: length;
. .
type nameN : length; }variable_list;
Unions:
Unions in C++ is a user defined data type that uses the same memory as
other objects from a list of objects. At an instance it contains only a single object. Syntax: union union-type-name{ type member-name; type member-name; }union-variables
Multiple Choice Questions
Q.1 The address of a variable temp of type float is
(A) *temp (B) &temp
(C) float& temp (D) float temp& Ans: B Q.2 What is the output of the following code
char symbol[3]={„a‟,„b‟,„c‟};
for (int index=0; index<3; index++) cout << symbol [index];
(A) a b c (B) “abc”
(C) abc (D) „abc‟ Ans: C
Q.3 If the variable count exceeds 100, a single statement that prints “Too many” is
(A) if (count<100) cout << “Too many”; (B) if (count>100) cout >> “Too many”; (C) if (count>100) cout << “Too many”;
(D) None of these. Ans: C
(A) 0 to 216 (B) -215 to 215 -1
(C) -27 to 27 -1 (D) 0 to 28 Ans: B
Q.5 If X=5 , Y=2 then yx∧ equals________. (where ∧ is a bitwise XOR operator)
(A) 00000111 (B) 10000010
(C) 10100000 (D) 11001000 Ans:A
Q.6 If an array is declared as int a[4] = {3, 0, 1, 2}, then values assigned toa[0] & a[4] will be ________
(A) 3, 2 (B) 0, 2
(C) 3, 0 (D) 0, 4 Ans: C
Q7. Which operator has the highest precedence?
(a) Unary (b) Binary
(c) Ternary (d) all of the above
Ans:A
Q8. Switch statement is used for:
(a) Multiple selection (b) Two set selection
(c) three set selection (d) none of the above Ans:A Q9. Which of the following operator takes only integer operands?
(a) + (b) X
Chapter -2
Class and Objects
Q.1. What is Class and Object in C++? Ans.: Class:-
A class is a way to bind the data and function together in a single unit. When we define a class , we create a new abstract data type that can be treated like other build in data type. The variables of class are called objects or instance of a class.
A class specification has two parts: i) Class Declaration
ii) Class Function definitions
A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations. For example we defined the Box data type using the keyword class as follows: class Box { public: double length; double breadth; double height; double getVolume(void) {
return length * breadth * height; }
};
The keyword public determines the access attributes of the members of the class that follow it. A public member can be accessed from outside the class anywhere within the scope of the class object. A class member can be defined as public, private or protected. By default members would be assumed as private. A member function of a class is a function that has its
definition or its prototype within the class definition like any other variable.
Creating Objects:-
A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two objects of class Box:
Box Box1; // Declare Box1 of type Box Box Box2;
A Class and Object Example
class Box{
public:
double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box // Member functions declaration double getVolume(void);
void setLength( double len ); void setBreadth( double bre ); void setHeight( double hei ); };
// Member functions definitions double Box::getVolume(void) {
return length * breadth * height; }
void Box::setLength( double len ) {
length = len; }
void Box::setBreadth( double bre ) {
breadth = bre; }
void Box::setHeight( double hei ) {
height = hei; }
// Main function for the program int main( )
{
Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here // box 1 specification Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // volume of box 1 volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl; // volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl; return 0;
}
When the above code is compiled and executed, it produces following result:
Volume of Box1 : 210 Volume of Box2 : 1560
Q2 What do you understand by class member function?
Ans. The member functions are set of functions that are applied to objects of that class. A function as a member of a class is also called a Method. A member function is declared like any of the functions we have used so far; it could or could not return a value.
When using functions on a class, the variables are used to hold or store values, called data, of the object, while member functions are used to perform assignments as related to the objects. One way you can control the data held by variables is to hide data from the “external world”. To achieve this, you should declare the member variables in the private section. After doing this, use the methods in the public section to help the class interact with the other objects or functions of the program.
Q3 What is an Array of Objects in C++?
Ans Arrays of variables of type "class" is known as "Array of objects". The "identifier" used to refer the array of objects is an user defined data type. #include <iostream.h>
const int MAX =100; class Details { private: int salary; float roll; public: void getname( ) {
cout << "\n Enter the Salary:"; cin >> salary;
cout << "\n Enter the roll:"; cin >> roll;
}
void putname( ) {
"and roll is" << roll << '\n'; } }; void main() { Details det[MAX]; int n=0; char ans; do{
cout << "Enter the Employee Number::" << n+1; det[n++].getname;
cout << "Enter another (y/n)?: " ; cin >> ans;
} while ( ans != 'n' ); for (int j=0; j<n; j++) {
cout << "\nEmployee Number is:: " << j+1; det[j].putname( );
} }
Result:
Enter the Employee Number:: 1 Enter the Salary:20
Enter the roll:30
Enter another (y/n)?: y
Enter the Employee Number:: 2 Enter the Salary:20
Enter the roll:30
Enter another (y/n)?: n
In the above example an array of object "det" is defined using the user defined data type "Details". The class element "getname()" is used to get the input that is stored in this array of objects and putname() is used to display the information.
Q4 What is Nested classes in C++?
Ans Nested class is a class defined inside a class, that can be used within the scope of the class in which it is defined. In C++ nested classes are not given importance because of the strong and flexible usage of inheritance. Its objects are accessed using "Nest::Display".
#include <iostream.h> class Nest { public: class Display { private: int s; public:
void sum( int a, int b) { s =a+b; }
void show( )
{ cout << "\nSum of a and b is:: " << s;} }; }; void main() { Nest::Display x; x.sum(12, 10); x.show(); } Result:
Sum of a and b is::22
In the above example, the nested class "Display" is given as "public" member of the class "Nest".
Q5 what is inline function in c++ ?
Ans C++ inline function is powerful concept that is commonly used with classes. If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time.
Any change to an inline function could require all clients of the function to be recompiled because compiler would need to replace all the code once again otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name and define the function before any calls are made to the function.
Following is an example which makes use of inline function #include <iostream>
inline int Max(int x, int y) {
return (x > y)? x : y; }
// Main function for the program main( )
{
cout << "Max (20,10): " << Max(20,10) << endl; cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl; return 0;
}
When the above code is compiled and executed, it produces following result:
Max (20,10): 20 Max (0,200): 200 Max (100,1010): 1010
Q6 What do you mean by friend function?
Ans A friend function is used for accessing the non-public members of a class. A class can allow non-member functions and other classes to access its own private data, by making them friends. Thus, a friend function is an ordinary function or a member of another class. The friend function is written as any other normal function, except the function declaration of these functions is preceded with the keyword friend. The friend function
must have the class to which it is declared as friend passed to it in argument.
Example to understand the friend function #include <iostream> using namespace std; class fri { private: int a,b; public: void test() { a=100; b=200; }
friend int compute(fri e1);
//Friend Function Declaration with keyword friend and with the object of class fri to which it is friend passed to it
};
int compute(fri e1) {
//Friend Function Definition which has access to private data return int(e1.a+e1.b)-5; } void main() { fri e; e.test();
cout << "The result is:" << compute(e);
//Calling of Friend Function with object as argument. }
Q7 What do you mean by static member function.
Ans The keyword static is used to precede the member function to make a member function static. The static member function has following properties:
1) A static function have access to only static member declared in the class. 2) A static member function can be called using the class names as :
Classname : : functionname;
3) A static member function acts as global for the data member of its class without affecting the rest of the program.
Q8 What do you mean by Dynamic Memory Allocation?
Ans Allocating memory
There are two ways that memory gets allocated for data storage: Compile Time (or static) Allocation
Memory for named variables is allocated by the compiler. Exact size and type of storage must be known at compile time For standard array declarations, this is why the size has to be constant
Dynamic Memory Allocation
Memory allocated "on the fly" during run time
dynamically allocated space usually placed in a program segment known as the heap or the free store
Exact amount of space or number of items does not have to be known by the compiler in advance.
For dynamic memory allocation, pointers are crucial
Dynamic Memory Allocation
We can dynamically allocate storage space while the program is running, but we cannot create new variable names "on the fly"
For this reason, dynamic allocation requires two steps: a) Creating the dynamic space.
b) Storing its address in a pointer (so that the space can be accesed) To dynamically allocate memory in C++, we use the new operator. De-allocation:
Deallocation is the "clean-up" of space being used for variables or other data storage
Compile time variables are automatically deallocated based on their known extent (this is the same as scope for "automatic" variables)
It is the programmer's job to deallocate dynamically created space To de-allocate dynamic memory, we use the delete operator
Q.9. What is constructor and Destructor in C++? Explain. Ans.: Constructor
A class constructor is a special member function of a class that is executed whenever we create new objects of that class.
A constructor will have exact same name as the class and it does not have any return type at all, not even void. Constructors can be very useful for setting initial values for certain member variables.
Types of Constructor
Default Constructor-: A constructor that accepts no parameters is known
as default constructor. If no constructor is defined then the compiler supplies a default constructor.
student :: student() {
rollno=0; marks=0.0; }
Parameterized Constructor -: A constructor that receives arguments/parameters, is called parameterized constructor.
student :: student(int r) {
rollno=r; }
Copy Constructor-: A constructor that initializes an object using values of
another object passed to it as parameter, is called copy constructor. It creates the copy of the passed object.
student :: student(student &t) {
rollno = t.rollno; }
Destructor
A destructor is a member function having sane name as that of its class preceded by ~(tilde) sign and which is used to destroy the objects that have been created by a constructor. It gets invoked when an object‟s scope is over.
~student() { }
Example : In the following program constructors, destructor and other
member functions are defined inside class definitions. #include<iostream> class CAdd { public: int one; CAdd(int two) {
cout << "A constructor is called" << endl; one=two;
}
CAdd() {
cout << "A default constructor is called " << endl; }
~CAdd() {
cout << "Destructing " << one << endl; } int add() { return(one+one); } }; main() { CAdd myobj1(4); CAdd myobj2;
cout << myobj1.one << endl; cout << "Enter a number : " ; cin >> myobj2.one;
cout << myobj2.add() << endl; return(0);
}
Q10 What are the special characteristic of constructors and destructors in c++?
Ans Characteristic of constructors and destructors (1) Constructors
(i) Constructor has the same name as that of the class it belongs. (ii) Constructor is executed when an object is declared.
(iii) Constructors have neither return value nor void.
(iv) The main function of constructor is to initialize objects and allocate appropriate memory to objects.
(v) Though constructors are executed implicitly, they can be invoked explicitly.
(vi) Constructor can have default and can be overloaded.
(vii) The constructor without arguments is called as default constructor. (2) Destructors
(i) Destructor has the same name as that of the class it belongs to and preceded by ~ (tilde).
(ii) Like constructor, the destructor does not have return type and not even void.
Q.11. What is inheritance?
Ans.: Inheritance:-Inheritance means using the Pre-defined Code This is very
Main Feature of OOP. With the help of inheritance we uses the code that is previously defined but always Remember, We are only using that code but not changing that code.
With the Advent of inheritance we are able to use pre-defined code and also able to add new code. All the pre-defined code is reside into the form of classes if we want to use that code then we have to inherit or extend that class.
The Class that is Pre-defined is called as Base or super Class and the class which uses the Existing Code is known as derived or sub class The Various Types of Inheritance those are provided by C++ are as followings: 1. Single Inheritance 2. Multilevel Inheritance 3. Multiple Inheritance 4. Hierarchical Inheritance 5. Hybrid Inheritance Q12 What are the types of Inheritance ? Ans
1) In Single Inheritance there is only one Super Class and Only one Sub Class Means they have one to one Communication between them
2) In Multilevel Inheritance a Derived class can also inherited by another class Means in this When a Derived Class again will be inherited by another Class then it creates a Multiple Levels.
3) Multiple Inheritances is that in which a Class inherits the features from two Base Classes When a Derived Class takes Features from two Base Classes.
4) Hierarchical Inheritance is that in which a Base Class has Many Sub Classes or When a Base Class is used or inherited by many Sub Classes.
5) Hybrid Inheritance: - This is a Mixture of two or More Inheritance and in this Inheritance a Code May Contains two or Three types of inheritance in Single Code.
Q13 What is a virtual base class? -
Ans When two or more objects are derived from a common base class, we can prevent multiple copies of the base class being present in an object derived from those objects by declaring the base class as virtual when it is being inherited. Such a base class is known as virtual base class. This can be achieved by preceding the base class‟ name with the word virtual.
Consider following example: class A
{
public: int i; };
class B : virtual public A {
public: int j; };
class C: virtual public A {
public: int k; };
class D: public B, public C {
public: int sum; }; main() { D ob;
ob.i = 10; //unambiguous since only one copy of i is inherited. ob.j = 20;
ob.k = 30;
ob.sum = ob.i + ob.j + ob.k;
cout << “Value of i is : ”<< ob.i<<”\n”;
cout << “Value of j is : ”<< ob.j<<”\n”; cout << “Value of k is :”<< ob.k<<”\n”;
cout << “Sum is : ”<< ob.sum <<”\n”; return 0;
}.
Q14 What are the types to access member?
Ans. Access Control
A derived class can access all the non-private members of its base class. Thus base-class members that should not be accessible to the member functions of derived classes should be declared private in the base class.
We can summarize the different access types according to who can access them in the following way:
Access public protected private
Same class yes yes yes
Derived classes yes yes no
Outside classes yes no no
A derived class inherits all base class methods with the following exceptions:
Constructors, destructors and copy constructors of the base class. Overloaded operators of the base class.
Q.1 The process of building new classes from existing one is called ______.
(A) Polymorphism (B) Structure
(C) Inheritance (D) Cascading Ans: C
Q.2 If a class C is derived from class B, which is derived from class A, all through public inheritance, then a class C member function can access (A) protected and public data only in C and B.
(B) protected and public data only in C. (C) rivate data in A and B.
(D) protected data in A and B. Ans:D
Q.3 Usually a pure virtual function
(A) has complete function body. (B) will never be called. (C) will be called only to delete an object.
(D) is defined only in derived class. Ans:D
Q4 Number of constructor in a class can be:
(a) minimum one (b) zero
(c) two (d) as many as required Ans:d
Q5 Name of a constructor is:
(a) user defined (b) same as class name
(c) same as program file name (d) none of the above Ans:b Q6. Constructor is involved :
(a) when class object is created (b) when class object is initialized (c) through an explicit call (d) none of the above Ans:a Q7. The number of copies created for a static data member of a class, when 10
class object are created would be:
(a) 0 (b) 1
(c) 2 (d) 4 Ans:B
Q8. A destructor :
(a) has a return type (b) may take parameters
(c) has same name of class (d) both b and a Ans:C
(a) has a return type (b) may take parameter
(c) has same name as class (d) both b and c Ans:D Q10. The member of a class by default are:
(a) Private (b) Protected
(c) Public (d) no default exists Ans:A
Q11 A new class can be derived from an existing class. This concept is called us:
(a) inheritance (b) polymorphism
(c) overloading (d) dynamic binding Ans:A
Q12 A C + + Class can hold?
(a) only data (b) only function
(c) both data and function (d) none of the above Ans:C
Q13 Among the following, which one is the scope resolution operator?
(a) * (b)
(c) : : (d) ! Ans:C
Q14. Cout is:
(a) a key word (b) an obect
(c) a library function (d) a variable Ans:B
Q15. The pure virtual functions are defined in:
(a) base class (b) drived class
(c) main program (d) both a and b
Ans:B
Q16. Inheritance is a way to: (a) make new classes
(b) pass arguments of objects of class
(c) add feature to existing classes without rewriting them
(d) Improve to existing classes without rewriting them Ans:C
(a) Public (b) Private
(c) Protected (d) Any of the above Ans:B
Q18. Friend keyword can be used for :
(a) a function (b) a class
(c) both function and class (d) a data member Ans:C
Q19 Inline functions ………..call overload:
(a) Increase (b) Reduce
Chapter -3
Polymorphism
Q1 What is function overloading in C++?
Ans. Function overloading: A feature in C++ that enables several functions of
the same name can be defined with different types of parameters or different number of parameters. This feature is called function overloading. The appropriate function will be identified by the compiler by examining the number or the types of parameters / arguments in the overloaded function. Function overloading reduces the investment of different function names and used to perform similar functionality by more than one function.
Consider a function print, which displays an int. As shown in the
following example, you can overload the function print to display other
types, for example, double and char*. You can have three functions with the
same name, each performing a similar operation on a different data type: #include <iostream>
using namespace std; void print(int i) {
cout << " Here is int " << i << endl; }
void print(double f) {
cout << " Here is float " << f << endl; }
void print(char* c) {
cout << " Here is char* " << c << endl; }
int main() { print(10); print(10.10); print("ten");
} Result is
Here is int 10 Here is float 10.1 Here is char* ten
Q2 What is operator overloading in C++?
Ans In C++ the overloading principle applies not only to functions, but to operators too. That is, of operators can be extended to work not just with built-in types but also classes. A programmer can provide his or her own operator to a class by overloading the built-in operator to perform some specific computation when the operator is used on objects of that class. // This example illustrates overloading the plus (+) operator.
#include <iostream> using namespace std; class complx { double real, imag; public:
complx( double real = 0., double imag = 0.); // constructor complx operator+(const complx&) const; // operator+() };
// define constructor
complx::complx( double r, double i ) {
real = r; imag = i; }
// define overloaded + (plus) operator
complx complx::operator+ (const complx& c) const {
result.real = (this->real + c.real); result.imag = (this->imag + c.imag); return result; } int main() { complx x(4,4); complx y(6,6);
complx z = x + y; // calls complx::operator+()
Q3 What do you mean by early binding and late binding?
Ans. Early Binding: Events occurring at compile time are known as early
binding. In the process of early binding all info which is required for a function call is known at compile time. Early binding is a fast and efficient process. Examples of early binding: function calls, overloaded function calls, and overloaded operators.
Late Binding: In this process all info which is required for a function call
is not known at compile time. Hence, objects and functions are not linked at run time. Late Binding is a slow process. However, it provides flexibility to the code. Example of Late Binding: Virtual functions.
Q4 What do you mean by Virtual Function:
Ans A virtual function is a function in a base class that is declared using the keyword virtual. Defining in a base class a virtual function, with another version in a derived class, signals to the compiler that we don't want static linkage for this function.
What we do want is the selection of the function to be called at any given point in the program to be based on the kind of object for which it is called. This sort of operation is referred to as dynamic linkage, or late
binding.
Q5 What do you mean by Pure Virtual Functions:
Ans. It's possible that you'd want to include a virtual function in a base class so that it may be redefined in a derived class to suit the objects of that class, but that there is no meaningful definition you could give for the function in the base class.
We can change the virtual function area() in the base class to the following:
class Shape { protected:
public:
Shape( int a=0, int b=0) {
width = a; height = b; }
// pure virtual function virtual int area() = 0; };
The = 0 tells the compiler that the function has no body and above virtual function will be called pure virtual function.
Q6 Explain Unary and binary operator overloading.
Ans The unary operators operate on a single operand and following are the examples of Uninary operators:
The increment (++) and decrement (--) operators. The unary minus (-) operator.
The logical not (!) operator.
The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as in !obj, -obj, and ++obj but sometime they can be used as postfix as well like obj++ or obj--.
Following example explain how minus (-) operator can be overloaded for prefix as well as postfix usage.
#include <iostream> using namespace std; class Distance { private:
int feet; // 0 to infinite int inches; // 0 to 12 public: // required constructors Distance(){ feet = 0; inches = 0; }
Distance(int f, int i){ feet = f;
inches = i; }
// method to display distance void displayDistance() {
cout << "F: " << feet << " I:" << inches <<endl; }
// overloaded minus (-) operator Distance operator- ()
{
feet = -feet; inches = -inches;
return Distance(feet, inches); } }; int main() { Distance D1(11, 10), D2(-5, 11); -D1; // apply negation D1.displayDistance(); // display D1 -D2; // apply negation D2.displayDistance(); // display D2 return 0; }
When the above code is compiled and executed, it produces following result:
F: -11 I:-10 F: 5 I:-11
Hope above example makes your concept clear and you can apply similar concept to overload Logical Not Operators (!).
Binary operators
The Binary operators take two arguments and following are the examples of Binary operators. You use binary operators very frequently like addition (+) operator, subtraction (-) operator and division (/) operator. Following example explain how addition (+) operator can be overloaded. Similar way you can overload subtraction (-) and division (/) operators. #include <iostream>
class Box {
double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box public:
double getVolume(void) {
return length * breadth * height; }
void setLength( double len ) {
length = len; }
void setBreadth( double bre ) {
breadth = bre; }
void setHeight( double hei ) {
height = hei; }
// Overload + operator to add two Box objects. Box operator+(const Box& b)
{
Box box;
box.length = this->length + b.length; box.breadth = this->breadth + b.breadth; box.height = this->height + b.height; return box;
} };
// Main function for the program int main( )
{
Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here // box 1 specification Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // volume of box 1 volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// Add two object as follows: Box3 = Box1 + Box2;
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0; }
When the above code is compiled and executed, it produces following result:
Volume of Box1 : 210 Volume of Box2 : 1560 Volume of Box3 : 5400
Q7 What is assignment operator overloading ?
Ans. We can overload the assignment operator (=) just as you can other operators and it can be used to create an object just like the copy constructor.
Following example explain how an assignment operator can be overloaded.
#include <iostream> using namespace std; class Distance { private:
int feet; // 0 to infinite int inches; // 0 to 12 public: // required constructors Distance(){ feet = 0; inches = 0; }
Distance(int f, int i){ feet = f;
inches = i; }
void operator=(const Distance &D ) {
feet = D.feet; inches = D.inches; }
// method to display distance void displayDistance() {
cout << "F: " << feet << " I:" << inches << endl; } }; int main() { Distance D1(11, 10), D2(5, 11); cout << "First Distance : "; D1.displayDistance();
cout << "Second Distance :"; D2.displayDistance();
// use assignment operator D1 = D2;
D1.displayDistance(); return 0;
}
When the above code is compiled and executed, it produces following result:
First Distance : F: 11 I:10 Second Distance :F: 5 I:11 First Distance :F: 5 I:11
Q8 What is free store in C++?
Ans. The free store is one of the two dynamic memory areas, allocated/freed by new/delete. Object lifetime can be less than the time the storage is allocated; that is, free store objects can have memory allocated without being immediately initialized, and can be destroyed without the memory being immediately deallocated. During the period when the storage is allocated but outside the object's lifetime, the storage may be accessed and manipulated through a void* but none of the proto-object's nonstatic members or member functions may be accessed, have their addresses taken, or be otherwise manipulated.
Q9 Explain Abstract classes.
Ans Abstract classes
An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function. You declare a pure virtual function by using a pure specifier (= 0) in the declaration of a virtual member function in the class declaration.
The following is an example of an abstract class: class AB {
public:
virtual void f() = 0; };
Function AB::f is a pure virtual function. A function declaration cannot have both a pure specifier and a definition. For example, the compiler will not allow the following:
struct A {
virtual void g() { } = 0; };
You cannot use an abstract class as a parameter type, a function return type, or the type of an explicit conversion, nor can you declare an object of an abstract class. You can, however, declare pointers and references to an abstract class. The following example demonstrates this:
struct A { virtual void f() = 0; }; struct B : A { virtual void f() { } }; // Error:
// Class A is an abstract class // A g();
// Error:
// Class A is an abstract class // void h(A);
A& i(A&); int main() { // Error:
// Class A is an abstract class // A a;
A* pa; B b; // Error:
// Class A is an abstract class // static_cast<A>(b);
}
Class A is an abstract class. The compiler would not allow the function declarations A g() or void h(A), declaration of object a, nor the static cast of b to type A.
Virtual member functions are inherited. A class derived from an abstract base class will also be abstract unless you override each pure virtual function in the derived class.
For example: class AB { public: virtual void f() = 0; }; class D2 : public AB { void g(); }; int main() { D2 d; }
The compiler will not allow the declaration of object d because D2 is an abstract class; it inherited the pure virtual function f()from AB. The compiler will allow the declaration of object d if you define function D2::g().
Note that you can derive an abstract class from a nonabstract class, and you can override a non-pure virtual function with a pure virtual function. You can call member functions from a constructor or destructor of an abstract class. However, the results of calling (directly or indirectly) a pure virtual function from its constructor are undefined. The following example demonstrates this:
struct A { A() { direct(); indirect(); }
virtual void direct() = 0;
virtual void indirect() { direct(); } };
The default constructor of A calls the pure virtual function direct() both directly and indirectly (through indirect()).
The compiler issues a warning for the direct call to the pure virtual function, but not for the indirect call.
Q.1 Overloading the function operator
(A) requires a class with an overloaded operator. (B) requires a class with an overloaded [ ] operator.
(C) allows you to create objects that act syntactically like functions.
(D) usually make use of a constructor that takes arguments. Ans:A
Q2. For operator overloading the operands should be of type:
(a) Minimum one (b) zero
(c) user defined (d) any type Ans:c
Q3. The word which makes the name of tan operator overloading function is: (a) the operator symbol (b) the key word operator
(c) the keyboard operator followed by the operator symbol
(d) user defined Ans:C
Q4. The operator over loading function can be :
(a) member function only (b) non member function only
(c) both a or b (d) none of the above Ans.C
Q5. Templates can be used:
(a) Functions only (b) classes only
(c) functions and classes both (d) none of the above Ans:C Q6. Which of the following operators can be over-loaded?
(a) ≫ (b) ? :
(c) both a and b (d) no such operator exists Ans:A Q7 Ability to take many forms is………..
(a) Polymorphism (b) Encapsulation
Chapter -4
Pointers & File Handling
Q.1. What is pointers ?
Ans.: A pointer is a variable whose value is the address of another variable. Like
any variable or constant, we must declare a pointer before we can work with it. The general form of a pointer variable declaration is:
type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type and var-name is the var-name of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration:
int *ip; // pointer to an integer double *dp; // pointer to a double float *fp; // pointer to a float char *ch // pointer to character
Q2 What are the arithmetic operators used on pointers ?
Ans There are four arithmetic operators that can be used on pointers: ++, --, +, -
Incrementing a Pointer:
We prefer using a pointer in our program instead of an array because the variable pointer can be incremented, unlike the array name which cannot be incremented because it is a constant pointer. The following program increments the variable pointer to access each succeeding element of the array:
#include <iostream> const int MAX = 3; int main ()
{
int var[MAX] = {10, 100, 200}; int *ptr;