E-Notes PDF All-Units 27042019042410AM
E-Notes PDF All-Units 27042019042410AM
1) What is Object Oriented Programming? Differentiate procedure oriented and object oriented programming language.
OR
List out characteristics of POP and OOP.
Object Oriented Programming is programming paradigm that represents concepts as objects that has data
fields and associated procedures known as methods.
1. Emphasis is on doing things not on data, 1. Emphasis is on data rather than procedure, means
means it is function driven object driven
2. Main focus is on the function and procedures 2. Main focus is on the data that is being operated
that operate on data
4. Large programs are divided into smaller 4. Large programs are divided into classes and objects
programs known as functions
5. Most of the functions share global data 5. Data is tied together with function in the data
structure
6. Data moves openly in the system from one 6. Data is hidden and cannot be accessed by external
function to another function functions
7. Adding of data and function is difficult 7. Adding of data and function is easy
10. Examples: C, Fortran, Pascal, etc… 10. Examples: C++, Java, C#, etc…
1 – Concepts of OOP
Example:
class employee // Class
{
char name[10]; // Data member
int id; // Data member
public:
void getdata() // Member function
{
cout<<”enter name and id of employee: ”;
cin>>name>>id;
}
}a; // Object Declaration
∙ In above example class employee is created and ‘a’ is object of this class.
∙ Object declaration can be also done in main() function as follows:
int main()
{
employee a;
}
Data Abstraction
∙ Just represent essential features without including the background details.
∙ They encapsulate all the essential properties of the objects that are to be created. ∙ The
attributes are sometimes called ‘Data members’ because they hold information. ∙ The functions
that operate on these data are sometimes called ‘methods’ or ‘member functions’. ∙ It is used to
implement in class to provide data security.
Encapsulation
∙ Wrapping up of a data and functions into single unit is known as encapsulation.
∙ The new class is called derived class and old class is called base class.
∙ The derived class may have all the features of the base class.
∙ Programmer can add new features to the derived class.
∙ For example, Student is a base class and Result is derived class.
Polymorphism
∙ A Greek word Polymorphism means the ability to take more than one form.
∙ Polymorphism allows a single name to be used for more than one related purpose. ∙ The
concept of polymorphism is characterized by the idea of ‘one interface, multiple methods’, ∙ That
means using a generic interface for a group of related activities.
∙ The advantage of polymorphism is that it helps to reduce complexity by allowing one interface to specify a
general class of action’. It is the compiler’s job to select the specific action as it applies to each situation. ∙ It
means ability of operators and functions to act differently in different situations.
1 – Concepts of OOP
Example:
int total(int, int);
int total(int, int, float);
Static Binding
∙ Static Binding defines the properties of the variables at compile time. Therefore they can’t be changed.
Dynamic Binding
∙ Dynamic Binding means linking of procedure call to the code to be executed in response to the call. ∙ It is
also known as late binding, because It will not bind the code until the time of call at run time. In other words
properties of the variables are determined at runtimes.
∙ It is associated with polymorphism and inheritance.
Message Passing
∙ A program contains set of object that communicates with each other.
∙ Basic steps to communicate
1. Creating classes that define objects and their behavior.
2. Creating objects from class definition
3. Establishing communication among objects.
∙ Message passing involves the object name, function name and the information to be sent.
Example: employee.salary(name);
In above statement employee is an object. salary is message, and name isinformation to be
sent. 3) List out benefits of OOP.
∙ We can eliminate redundant code though inheritance.
∙ Saving development time and cost by using existing module.
∙ Build secure program by data hiding.
∙ It is easy to partition the work in a project based on object.
∙ Data centered design approach captures more details of a programming model.
∙ It can be easily upgraded from small to large system.
∙ It is easy to map objects in the problem domain to those in the program.
∙ Through message passing interface between objects makes simpler description with external system. ∙
Software complexity can be easily managed.
2 – C++ Basics
1) What is C++? Explain Structure of C++ Program.
∙ C++ is an object oriented programming language.
∙ It is a superset of C language and also called as extended version of C language.
∙ It was developed by Bjarne Stroustrup at AT&T Bell lab in New Jersey, USA in the early 1980’s.
∙ Structure of C++ program is as follow.
Include Files
Main function
∙ In any program first write header files like as iostream.h, conio.h, etc..as per requirement of program.
∙ After header file write class declaration or definition as per your planning.
∙ After class, define all member functions which are not define but declare inside the class.
∙ In last write main function without main function program execution is not possible.
Example:
#include <iostream> //Header File
using namespace std;
2 – C++ Basics
Keywords:
∙ They are explicitly reserved identifiers and cannot be used as names for the program variables or other
user-defined program elements.
Ex: int, class, void etc.
Identifiers:
∙ They refer to the names of variables, functions, arrays, classes etc., created by the programmer. ∙
Each language has its own rules for naming these identifiers.
∙ Following are common rules for both C and C++:
o Only alphabetic characters, digits and underscores are permitted.
o The name cannot start with a digit.
o Uppercase and lowercase letters are distinct.
o A declared keyword cannot be used as a variable name.
Constants:
∙ Like variables, constants are data storage locations. But variables can vary, constants do not change. ∙ You
must initialize a constant when you create it, and you can not assign new value later, after constant is
initialized.
Defining constant using #define:
∙ #define is a preprocessor directive that declares symbolic constant.
Example syntax:
#define PI 3.14
∙ Every time the preprocessor sees the word PI, it puts 3.14 in the text.
Example:
#include<iostream>
using namespace std;
#define PI 3.14
int main()
{
int r,area;
cout<<”Enter Radius :”;
cin>>r;
area=PI*r*r;
cout<<”Area of Circle = ”<<area;
return 0;
}
Output:
Enter Radius :5
Area of Circle = 78.5
2 – C++ Basics
∙ int
∙ float
Derived data type
∙ char
∙ void ∙ Array
∙ Pointer
∙ Function
∙ Reference
∙ Class
∙ Structure
∙ Union
∙ enum
Secondary data type
2 – C++ Basics
1. Arrays
2. Function
3. Pointers
∙ We cannot use the derived data type without use of primary data type.
∙ Array: An array is a fixed-size sequenced collection of elements of the same data type. ∙
Pointer: Pointer is a special variable which contains address of another variable.
∙ Function: A Group of statements combined in one block for some special purpose.
* Multiplication
/ Division
% Modulo division
2. Relational Operators
Relational operators are used to compare two numbers and taking decisions based on their relation.
Relational expressions are used in decision statements such as if, for, while, etc…
2 – C++ Basics
== is equal to
!= is not equal to
3. Logical Operators
Logical operators are used to test more than one condition and make decisions
&& logical AND (Both non zero then true, either is zero
then false)
|| logical OR (Both zero then false, either is non zero then true)
! logical NOT (non zero then false, zero then true)
4. Assignment Operators
Assignment operators are used to assign the result of an expression to a variable. C++ also supports
shorthand assignment operators which simplify operation with assignment
+= a += 1 is same as a = a + 1
-= a -= 1 is same as a = a - 1
*= a *= 1 is same as a = a * 1
/= a /= 1 is same as a = a / 1
%= a %= 1 is same as a = a % 1
a++ is postfix, the expression is evaluated first and then the value is
++a is prefix, the value is incremented first and then the expression is
-- Decrements value by 1.
a-- is postfix, the expression is evaluated first and then the value is
--a is prefix, the value is decremented first and then the expression is
6. Conditional Operator
2 – C++ Basics
A ternary operator is known as Conditional Operator.
exp1?exp2:exp3 if exp1 is true then execute exp2 otherwise exp3
| bitwise OR
^ bitwise exclusive OR
8. Special Operators
& Address operator, it is used to determine address of the variable.
* Pointer operator, it is used to declare pointer variable and to get value from it.
2 – C++ Basics
∙ The pointer_variable holds the address of the memory space allocated.
∙ For example:
p=new int;
q=new float;
∙ Type of ‘p’ is integer and type of ‘q’ is float.
2 – C++ Basics
∙ Without scope resolution operator all variable will refer local value.
Example:
#include <iostream.h>
int m=10;
int main()
{
int m=20;
{
int k=m;
int m=30;
cout<<"we are in inner block\n";
cout<<"k="<<k<<"\n";
cout<<"m="<<m<<"\n";
cout<<"::m="<<::m<<"\n";
}
cout<<"we are in outer block\n";
cout<<"m="<<m<<"\n";
cout<<"::m="<<::m<<"\n";
return 0;
}
Output:
we are in inner block
k=20
m=30
we are in outer block
m=20
::m=20
->* To access a member using a pointer to the object and a pointer to that member.
Explicit conversion:
∙ C++ permits explicit type conversion of variables or expressions using the type cast operator.
2 – C++ Basics
∙ Syntax: type_name (expression)
∙ Example: average = sum/float(i);
∙ Alternatively we can use typedef to create an identifier of the required type and use it in the functional
notation.
Example:
typedef int * int_ptr;
p = int_ptr(q);
Example:
#include<iostream>
using namespace std;
int main()
{
int intvar=5;
float floatvar=3.5;
cout<<"intvar = "<<intvar;
cout<<"\nfloatvar = "<<floatvar;
cout<<"\nfloat(intvar) = "<<float(intvar);
cout<<"\nint(floatvar) = "<<int(floatvar);
}
Output:
intvar = 5
floatvar = 3.5
float(intvar) = 5
int(floatvar) = 3
Call By Reference
∙ In call by reference, reference is passed during function call.
∙ The formal arguments in the called function become aliases to the actual function call. ∙ In call by
reference the original value in calling function will change after execution of function. Example:
#include<iostream>
using namespace std;
void swap(int &a, int &b) // It is the only difference from above program
{
int temp=a;
a=b;
b=temp;
}
int main()
{
int a,b;
cout<<"Enter two numbers:";
cin>>a>>b;
swap(a,b);
cout<<"a="<<a<<"b="<<b;
return 0;
}
Output:
Enter value of a and b:
4
5
| 2140705 – OBJECT ORIENTED PROGRAMMING WITH C++
Hardik A. Doshi, CE Department 13
3 – C++ Functions
After swapping a = 5 and b = 4
2) What is inline function? Explain with example.
∙ The functions can be made inline by adding prefix inline to the function definition.
∙ An inline function is a function that is expanded in line when it is invoked.
∙ The complier replaces the function call with the corresponding function code.
∙ Inline function saves time of calling function, saving registers, pushing arguments onto the stack and
returning from function.
∙ Preprocessor macros are popular in C, which has similar kind of advantages mentioned above. ∙
The major drawback of macros is that they are not really functions.
∙ Therefore, the usual error checking does not occur during execution of macros.
∙ We should be careful while using inline function. If function has very few lines of code and simple expressions
then only it should be used.
∙ Critical situations for inline function:
1) If a loop, a switch or a goto exists in function body.
2) If function is not returning any value.
3) If function contains static variables.
4) If function is recursive.
Example:
inline int cube(int n)
{
return n*n*n;
}
int main()
{
int c;
c = cube(10);
cout<<c;
}
∙ Function call is replaced with expression so c = cube(10); becomes c=10*10*10; at compile time.
3 – C++ Functions
{
cout<< "a= " << a << ", b= " << b<<endl;
}
int main()
{
f();
f(10);
f(10, 99);
return 0;
}
Output:
a=0 , b=0
a=10 ,b=0
a=10, b=99
3 – C++ Functions
}
Output: Sum = 30
∙ add is a friend function of the class numbers so it can access all members of the class(private, public and
protected).
∙ Member functions of one class can be made friend function of another class, like…
class X
{
………………………………………
int f();
};
class Y
{
………………………………………
friend int X :: f();
};
∙ The function f is a member of class X and a friend of class Y.
∙ We can declare all the member functions of one class as the friend functions of another class. In such cases,
the class is called a friend class, like class X is the friend class of class Z
class Z
{
………………………………………
friend class X;
……………………………………….
};
3 – C++ Functions
void Add(int num1, int num2, int num3) //Funciton 3
{
cout<<num1 + num2 + num3 <<endl;
}
};
int main()
{
Math m;
m.Add(10,20); \\ Calls function 1
m.Add(10.15, 25.70); \\ Calls function 2
m.Add(1,2,3); \\ Calls function 3
}
Output:
30
35.85
6
?: Conditional Operator
3 – C++ Functions
{
a=10;
b=20’
}
void operator -() //Unary Member Function
{
a = a - 5;
b = b - 5;
}
void disp()
{
cout<<"\nThe value of a="<<a;
cout<<"\nThe value of b="<<b;
}
};
int main()
{
sample S;
S.getdata();
-S; //Call Unary Member Function
S.disp();
getch();
return 0;
}
class sample
{
int a,b;
public:
void getdata()
{
a=10;
b=20;
}
friend sample operator +(sample A) //Unary Friend Function
{
A.a = A.a + 5;
A.b = A.b + 5;
return A;
}
void disp()
{
cout<<"\nThe value of a="<<a;
cout<<"\nThe value of b="<<b;
}
};
int main()
{
sample S;
S.getdata();
S=+S; //Call Unary Friend Function
S.disp();
getch();
return 0;
}
3 – C++ Functions
∙ Example for Binary Operator Overloading
#include <iostream>
using namespace std;
class complex
{
float real, imag;
public:
complex(float _real, float _imag) // constructor
{
real = _real;
imag = _imag;
}
void disp()
{
cout<<"The value of real="<<real;
cout<<"The value of imag="<<imag;
}
void operator +(complex c) //Binary Member function
{
real = real + c.real;
imag = imag + c.imag;
}
};
int main()
{
complex x(4,4);
complex y(6,6);
x + y; // Call Binary Member Function
x.disp();
getch();
return 0;
}
∙ A class is a template that specifies the attributes and behavior of things or objects.
∙ A class is a blueprint or prototype from which objects are created.
∙ A class is the implementation of an abstract data type (ADT).
∙ It defines attributes and methods.
Object declaration:
∙ In following example class employee is created and ‘a’ is object of this class.
class item
{
// data members and member functions
}a;
∙ In above syntax class name is item, and a is object of that class
∙ Object declaration can be also done in main() function as follows:
int main()
{
item a;
}
Example:
#include<iostream>
using namespace std;
∙ The member functions are created and placed in the memory space only once when they are defined as part
of a class specification.
∙ No separate space is allocated for member functions when the objects are created.
∙ Only space for member variable is allocated separately for each object.
∙ A separate memory location for the objects happens, because the member variables will hold different data
values for different objects.
Member function 1
Memory created when
Functions defined
Object 1 Object 2 Object 3
Member function 1 Member
Member function 1 Member
Memory created when
Member function 1
Member function 1
Example:
class item
{
public:
int id, cost;
void getdata();
};
int main()
{
item x,y,z;
}
∙ In above example each object x, y and z has separate space for both id and cost. ∙
Means value of id and cost can be different for each object.
∙ But no default space is allocated to function when object is declared.
∙ Required separate space is allocated to function during calling of that function.
3) Explain Public and Private Access modifier (specifier) for C++ classes.
Public:
∙ Public members of the class are accessible by any program from anywhere.
∙ There are no restrictions for accessing public members of a class.
∙ Class members that allow manipulating or accessing the class data are made public.
Private:
∙ Private members of the class can be accessed within the class and from member functions of the class. ∙
They cannot be accessed outside the class or from other programs, not even from inherited class. ∙
Encapsulation is possible due to the private access modifier.
∙ If one tries to access the private members outside the class then it results in a compile time error. ∙
If any other access modifier is not specified then member default acts as Private member.
Example:
#include<iostream>
using namespace std;
class ABC
{
public:
int a;
private:
int b;
};
| 2140705 – OBJECT ORIENTED PROGRAMMING WITH C++
Hardik A. Doshi, CE Department 22
int main()
{
ABC x;
x.a=5;
cout<<"Value of public variable = "<<x.a;
}
Output:
5
4) Explain Static data members and static member functions with example.
Example:
#include<iostream>
using namespace std;
class item
{
int number;
static int count; // static variable declaration
public:
void getdata(int a)
{
number = a;
count++;
}
| 2140705 – OBJECT ORIENTED PROGRAMMING WITH C++
Hardik A. Doshi, CE Department 23
Output:
5) What is constructor? List out characteristics of constructors.
Properties of constructor:
∙ Constructor is invoked automatically whenever an object of class is created.
∙ Constructor name must be same as class name.
∙ Constructors should be declared in the public section because private constructor cannot be invoked outside
the class so they are useless.
∙ Constructors do not have return types and they cannot return values, not even void.
∙ Constructors cannot be inherited, even though a derived class can call the base class constructor. ∙
Constructors cannot be virtual.
∙ An object with a constructor cannot be used as a member of a union.
∙ They make implicit calls to the operators new and delete when memory allocation is required. 6)
1. Default constructor:
∙ Default constructor is the one which invokes by default when object of the class is created. ∙ It is
generally used to initialize the value of the data members.
∙ It is also called no argument constructor.
3. Copy constructor
∙ A copy constructor is used to declare and initialize an object from another object. ∙ For
example, integer(integer &i); OR integer I2(I1);
∙ Constructor which accepts a reference to its own class as a parameter is called copy constructor.
Example:
class integer
{
int m, n;
public:
integer(rectangle &x) // Copy constructor
{
m = x.m;
n = x.n;
| 2140705 – OBJECT ORIENTED PROGRAMMING WITH C++
Hardik A. Doshi, CE Department 25
Example:
#include<iostream>
using namespace std;
class rectangle
{
int length, width;
public:
rectangle() // Default constructor
{
length=0;
width=0;
}
rectangle(int _length, int _width) // Parameterized constructor
{
length = _length;
width = _width;
}
rectangle(rectangle &_r) // Copy constructor
{
length = _r.length;
width = _r.width;
}
………………………………
// other functions for reading, writing and processing can be written
here
………………………………
};
int main()
{
rectangle r1; // Invokes default constructor
rectangle r2(10,10); // Invokes parameterized constructor
rectangle r3(r2); // Invokes copy constructor
}
∙ Destructor is used to destroy the objects that have been created by a constructor.
∙ Destructor is a member function whose name must be same as class name but is preceded by a tilde (~). ∙
Destructor never takes any argument nor it returns any value nor it has return type. ∙ Destructor is invoked
automatically by the complier upon exit from the program.
∙ Destructor should be declared in the public section
Example:
#include<iostream.h>
using namespace std;
class rectangle
{
| 2140705 – OBJECT ORIENTED PROGRAMMING WITH C++
Hardik A. Doshi, CE Department 26
}
// other functions for reading, writing and processing can be written
here
};
int main()
{
rectanble x; // default constructor is called for this object
}
8) Explain use of objects as function arguments with example.
∙ Like any other data type function may be used as a function argument. It can be done in following two
ways:
1. A copy of the entire object is passed to the function
∙ This method is call pass by value.
∙ Since copy of the object is passed to the function, any changes made to the object inside the function
do not affect the object used to call the function.
2. Only the address of the object is transferred to the function.
∙ This method is called pass-by-reference.
∙ When an address of the object is passed, the called function works directly on the actual object used
in the call.
∙ This means that any changes made to the object inside the function will reflect in the actual object. ∙
This method is more efficient because it requires passing only addresses of the object, not an entire
object.
Example:
#include<iostream>
using namespace std;
clas time
{
int hours;
int minutes;
public:
void gettime(int h, int m)
{
hours=h;
minutes=m;
}
void puttime(void)
{
cout<<hours<<” hours and”;
| 2140705 – OBJECT ORIENTED PROGRAMMING WITH C++
Hardik A. Doshi, CE Department 27
int main()
{
time t1, t2, t3;
t1.gettime(2,45); //get t1
t2.gettime(3,30); //get t2
t3.sum(t1,t2); //t3 = t1 + t2
cout<<”t1 = ”; t1.puttime(); //display t1
cout<<”t2 = ”; t2.puttime(); //display t2
cout<<”t3 = ”; t3.puttime(); //display t3
return 0;
}
?: Conditional Operator
#include <iostream>
using namespace std;
class sample
{
int a,b;
public:
void getdata()
{
a=10;
b=20;
}
void operator -() //Unary Member Function
{
a = a - 5;
b = b - 5;
}
void disp()
{
cout<<"\nThe value of a="<<a;
cout<<"\nThe value of b="<<b;
}
};
int main()
{
sample S;
S.getdata();
-S; //Call Unary Member Function
S.disp();
getch();
return 0;
}
Output:
The value of a=5
The value of b=15
#include <iostream>
using namespace std;
class sample
{
int a,b;
public:
void getdata()
{
a=10;
b=20;
}
friend sample operator +(sample A) //Unary Friend Function
{
A.a = A.a + 5;
A.b = A.b + 5;
return A;
| 2140705 – OBJECT ORIENTED PROGRAMMING WITH C++
Hardik A. Doshi, CE Department 29
Output:
The value of a=15
The value of b=25
class complex
{
float real, imag;
public:
complex(float _real, float _imag) // constructor
{
real = _real;
imag = _imag;
}
void disp()
{
cout<<"The value of real="<<real;
cout<<"The value of imag="<<imag;
}
void operator +(complex c) //Binary Member
function {
real = real + c.real;
imag = imag + c.imag;
}
};
int main()
{
complex x(4,4);
complex y(6,6);
x + y; // Call Binary Member Function
x.disp();
getch();
return 0;
}
Output:
The value of real=10
The value of imag=10
class complex
{
| 2140705 – OBJECT ORIENTED PROGRAMMING WITH C++
Hardik A. Doshi, CE Department 30
Output:
The value of real=10
The value of imag=10
10) List out various type conversion techniques? Explain basic to class type conversion with example.
∙ C++ provides mechanism to perform automatic type conversion if all variable are of basic type. ∙ For user
defined data type programmers have to convert it by using constructor or by using casting operator.
∙ Three type of situation arise in user defined data type conversion.
1. Basic type to Class type
2. Class type to Basic type
3. Class type to Class type
∙ Now we will see each situation with example
class sample
{
float a;
public:
sample(){}
sample(int x) //Constructor to convert Basic to Class type
{
a=x;
| 2140705 – OBJECT ORIENTED PROGRAMMING WITH C++
Hardik A. Doshi, CE Department 31
4 – Objects and Classes
}
void disp()
{
cout<<"The value of a="<<a;
}
};
int main()
{
int a=10;
sample S;
S=a; //Basic to class type conversion
S.disp();
return 0;
}
Output:
The value of a=10
11) Explain type conversion for class to basic type with example.
∙ The Class type to Basic type conversion is done by using Casing Operator. ∙
The casting operator function should satisfy the following conditions.
1. It must be a class member.
2. It must not specify a return type.
3. It must not have any arguments.
Example:
#include <iostream>
using namespace std;
class sample
{
float a;
public:
sample()
{
a=10.23;
}
operator int();
};
sample:: operator int() //Casting operator function
{
int x;
x=a;
return x;
}
int main()
{
sample S;
int y= S; // Class to Basic conversion cout<<"The value
of y="<<y;
getch();
return 0;
}
| 2140705 – OBJECT ORIENTED PROGRAMMING WITH C++
Hardik A. Doshi, CE Department 32
12) Explain type conversion for class type to another class type with example.
∙ The class to class conversion is done by both constructor and casting operator. ∙
If conversion take place at source class, then by casting operator.
operator destination_class_name() //Definition of Casting operator {
//Create object of destination class
//write statement to convert value
// Return objecct of destination class
}
∙ If conversion take place at destination class, then by constructor.
Constructor_of_Destination_Class(Source_Class Object_Name)
{
//Statement for conversion
}
∙ We cannot convert at a time in both source and destination class.
Example:
#include <iostream>
using namespace std;
invent2(invent1 p)
{
code = p.getcode();
value= p.getitems()*p.getprice();
}
};
int main()
{
invent s1(100,5,140.0);
invent2 d1;
float total_value;
total_value =s1;
d1=s1;
cout<<”product details-invent1 type”<<”\n”;
s1.putdata();
cout << ”\nstock value”<<”\n”;
cout << “value =” <<total_value<<”\n\n”;
Inheritance is the process, by which class can acquire the properties and methods of another class.
The mechanism of deriving a new class from an old class is called inheritance.
The new class is called derived class and old class is called base class.
The derived class may have all the features of the base class and the programmer can add new features
to the derived class.
Types of Inheritance:
Single Inheritance If a class is derived from a single class then it is called single inheritance.
Class B is derived from class A
A
Multilevel Inheritance A class is derived from a class which is derived from another class then it is
called multilevel inheritance
Here, class C is derived from class B and class B is derived from class
A
A, so it is called multilevel inheritance.
Multiple Inheritance If a class is derived from more than one class then it is called multiple inheritance.
Here, class C is derived from two classes,
ABC
class A and class B.
Hierarchical Inheritance If one or more classes are derived from one class then it is called hierarchical
inheritance.
BCD
Hybrid Inheritance It is a combination of any above inheritance types. That is either multiple or
multilevel or hierarchical or any other combination.
public:
A
void dispA()
{
Here, class B and class C are derived from class A
BCD and class D is derived from class B and class C.
class D
{
public:
void dispD()
{
cout<<"class D method"<<endl;
}
};
{
cout<<"class E method";
}
};
int main()
{
A a;
B b;
C c;
D d;
E e;
F f;
b.displayA();
f.displayF();
f.displayA();
}
Output:
class A method
class A method
class D method
class C method
Class B and class E are derived from class A so it is example of Hierarchal Inheritance. Class F is
derived from class B and class C, class B is derived from class A so displayA() is not a member of class F then
also we can access it using object of class F.
Protected:
Protected members of the class can be accessed within the class and from derived class but cannot be
accessed from any other class or program.
It works like public for derived class and private for other programs
Example:
#include<iostream>
using namespace std;
class A
{
protected:
int a;
public:
void getdata()
{
cout<<"Enter value of a:";
cin>>a;
}
};
class B:public A
{
public:
void show()
{
cout<<"Value of a is:"<<a;
}
};
int main()
{
B x;
x.getdata();
x.show();
}
Output:
Enter value of a:5
Value of a is:5
If base class and derived class have member functions with same name and arguments. If you create
an object of derived class and write code to access that member function then, the member function in
derived class is only invokes.
Means the member function of derived class overrides the member function of base class.
This is called function overriding or method overriding in C++.
Example:
#include<iostream>
using namespace std;
class A
{
public:
void display()
{
cout<<"This is parent class";
}
};
class B:public A
{
public:
void display() // overrides the display() function of class A
{
cout<<"\nThis is child class";
}
};
int main()
{
B x;
x.display(); // method of class B invokes, instead of class A
}
Output:
This is child class
In hybrid inheritance child class has two direct parents which themselves have a common base class.
So, the child class inherits the grandparent via two seperate paths. it is also called as indirect parent class.
All the public and protected member of grandparent are inherited twice into child.
BC
For example:
class A
{
public:
int i;
};
If we use virtual base class, then it will inherit only single copy of member of base class to child class.
6) List out various situations for the execution of base class constructor in inheritance.
It allows a single name to be used for more than one related purpose.
Polymorphism
Function Overloading:
Function overloading is the practice of declaring the same function with different signatures. The same
function name will be used with different number of parameters and parameters of different type.
Operator Overloading:
Operator overloading is the ability to tell the compiler how to perform a certain operation based on its
corresponding operator’s data type.
Like + performs addition of two integer numbers, concatenation of two string variables and works totally
different when used with objects of time class.
Dynamic binding is the linking of a routine or object at runtime based on the conditions at that
moment. It means that the code associated with a given procedure call is not known until the time of
the call. At run-time, the code matching the object under current reference will be called.
Virtual Function:
Virtual function is a member function of a class, whose functionality can be over-ridden in its derived
classes.
The whole function body can be replaced with a new set of implementation in the derived class.
It is declared as virtual in the base class using the virtual keyword.
class item
{
int code;
float price;
public:
void getdata(int a,float b)
{
code =a;
price=b;
}
void show(void)
{
cout<<”code”<<code<<”\n”:
cout<<”price”<<price<<”\n”;
}
};
const int size =2;
int main()
{
item *p =new item[size];
item *d = p;
int x, i;
float y;
d->show();
d++;
}
return 0;
}
Here S is an object and getdata() is a member function. So, ‘this’ pointer will point or set to the address of
object S.
Suppose ‘a’ is private data member, we can access it only in public member function like as follows
a=50;
Example:
#include <iostream>
using namespace std;
class sample
{
int a;
public:
sample()
{
a=10;
}
void disp(int a)
{
cout<<"The value of argument a="<<a;
cout<<"\nThe value of data member a="<<this->a;
}
};
int main()
{
sample S;
S.disp(20);
return 0;
}
Output:
The value of argument a=20
The value of data member a=10
The most important advantage of ‘this’ pointer is, If there is same name of argument and data member
than you can differentiate it.
By using ‘this’ pointer we can access the data member and without ‘this’ we can access the argument in
same function.
We can use pointers not only to the base objects but also to the objects of derived
classes. A single pointer variable can be made to point to objects belonging to different
classes. For example:
B *ptr //pointer to class B type variable
B b; //base object
D d; // derived object
ptr = &b; // ptr points to object b
In above example B is base class and D isa derived class from B, then a pointer declared as a pointer to B
and point to the object b.
We can access those members of derived class which are inherited from base class by base class pointer.
But we cannot access original member of derived class which are not inherited by base class pointer.
We can access original member of derived class which are not inherited by using pointer of derived class.
Example:
#include <iostream>
using namespace std;
class base
{
public:
int b;
void show()
{
cout<<"\nThe value of b"<<b;
}
};
class derived:public base
{
public:
int d;
void show()
{
cout<<"\nThe value of b="<<b
<<"\nThe value of d="<<d;
}
};
int main()
{
base B;
derived D;
base *bptr;
bptr=&B;
cout<<"\nBase class pointer assign address of base class object";
bptr->b=100;
bptr->show();
bptr=&D;
bptr->b=200;
cout<<"\nBase class pointer assign address of derived class object";
bptr->show();
derived *dptr;
dptr=&D;
cout<<"\nDerived class pointer assign address of derived class object";
dptr->d=300;
dptr->show();
return 0;
}
Output:
Base class pointer assign address of base class object
The value of b100
Base class pointer assign address of derived class object
The value of b200
Derived class pointer assign address of derived class object
The value of b=200
The value of d=300
Base class and derived class have same function name and base class pointer is assigned address of
derived class object then also pointer will execute base class function.
To execute function of derived class, we have to declare function of base class as virtual. To declare
virtual function just uses keyword virtual preceding its normal function declaration. After making virtual
function, the compiler will determine which function to execute at run time on the basis of assigned address
to pointer of base class.
Example:
#include <iostream>
using namespace std;
class base
{
public:
void disp()
{
cout<<"\nSimple function in base class";
}
virtual void show()
{
cout<<"\nVirtual function of Base class";
}
};
int main()
{
base B;
derived D;
base *bptr;
bptr=&B;
cout<<"\nBase class pointer assign address of base class object";
bptr->disp();
bptr->show();
bptr=&D;
cout<<"\nBase class pointer assign address of derived class object";
bptr->disp();
bptr->show();
return 0;
}
Output:
Base class pointer assign address of base class object
Simple function in base class
Virtual function of Base class
Base class pointer assign address of derived class object
Simple function in base class
Same name with virtual function of base class in derived class
But, runtime polymorphism using virtual functions is achieved only when a virtual function is accessed
through a pointer to the base class.
Example:
#include<iostream>
#include<cstring>
using namespace std;
class media
{
protected:
char title[50];
float price;
public:
media(char *s, float a)
{
strcpy(title, s);
price = a;
}
void book::display()
{
cout<<”\nTitle:”<<title;
cout<<”\nPages:”<<pages;
cout<<”\nPrice:”<<pages;
}
void tape::display()
{
cout<<”\nTitle:”<<title;
cout<<”\nPlay time:”<<pages;
cout<<”\nPrice:”<<pages;
}
int main()
{
char * title=new char[30];
float price, time;
int pages;
// book details
cout<<”\n enter book details\n”;
cout<<”\n title: ”;
cin>>title;
cout<<”\n price: ”;
cin>>price;
cout<<”\n pages: ”;
cin>>pages;
cout<<”Price: ”;
cin>>price;
cout<<”Play time (mins):”;
cin>>time;
tape tape1(title, price, time);
media* list[2];
list[0] = &book1;
list[1] = &tape1;
cout<<”\n ………BOOK………”;
list[0] -> display();
cout<<”\n …………TAPE………”;
list[i] -> display();
return 0;
}
We can say empty function. A pure virtual function has no definition relative to the base class.
Programmers have to redefine pure virtual function in derived class, because it has no definition in base
class.
A class containing pure virtual function cannot be used to create any direct objects of its own.
This type of class is also called as abstract class.
Syntax:
virtual void display() = 0; OR virtual void display() {}
Hardik Doshi, Ishan Rajani 48
Darshan Institute of Engineering & Technology 140705 – OOP with C++ Computer Engineering Unit - 7 IO
and File Management
ios
pointer
istream ostream
streambuf
input Output
iostream
ios (General Contains basic facilities that are used by all other input and output
I/O stream
classes. Also contains a pointer to a buffer object.
class)
Declares constants and functions that are necessary for handling formatted input
and output functions.
iostream (I/O Inherits the properties of ios, istream and ostream through multiple inheritance and
stream) thus contains all the input and output functions.
C++ language provides a set of standard built-in functions which will do the work of reading and displaying
data or information on the I/O devices during program execution.
Such I/O functions establish an interactive communication between the program and user.
Function Syntax Use
cout cout<<” ”<<” ”; To display character, string and number on output device.
cin cin>> var1>>var2; To read character, string and number from input device.
get(char*) char ch; To read character including blank space, tab and newline
get(void) char ch; To read character including blank space, tab and
ch=cin.get(); newline character from input device. It will returns
input character.
getline() char name[20]; It is used to reads a whole line of text that ends with
int size=10; a newline character or size -1 character.
cin.getline(name,size); First argument represents the name of string and
second argument indicates the number of character to
be read.
write() char name[20]; It is used to display whole line of text on output device.
int size=10; First argument represents the name of string and second
cout.write(name,size) argument indicates the number of character to be display.
;
{
int size=5;
char name[50];
cin.getline(name,size); //getline()
cout.write(name,size); //write
return 0;
}
3) List out and explain functions and manipulators used for Formatted I/O operations.
fill() cout.fill('character') To specify a character that is used to fill the unused portion
;
of a field.
setf() cout.setf(arg1, arg2); To specify format flags that can control the form of
output display such as left or right justification.
The arg1 is formatting flags defined in the ios class. And arg2 is known as bit field specifies the group to
which the formatting flags belong.
for(int i=1;i<=10;i++)
{
cout.setf(ios::internal, ios::adjustfield);
cout.width(5);
cout<<i;
cout.setf(ios::right, ios::adjustfield);
cout.width(20);
cout<<sqrt(i)<<"\n";
}
cout.setf(ios::scientific, ios::floatfield);
cout<<"\nSQRT(100)="<<sqrt(100)<<"\n";
return 0;
}
Output:
value*******SQRT OF VALUE
+...1.............+1.0000
+...2.............+1.4142
+...3.............+1.7321
+...4.............+2.0000
+...5.............+2.2361
+...6.............+2.4495
+...7.............+2.6458
+...8.............+2.8284
+...9.............+3.0000
+..10.............+3.1623
SQRT(100)=+1.0000e+01
setiosflags() To specify format flags that can control the form of output
display such as left or right justification.
double term,sum=0;
for(int n=1;n<=10;n++)
{
term=1.0/float(n);
return 0;
}
Output:
n Inverse of n Sum of terms
1 1.0000e+00 1.0000
short. ios
iostrem file
fstream base
Hardik Doshi, Ishan Rajani 54
Darshan Institute of Engineering & Technology 140705 – OOP with C++ Computer Engineering Unit - 7 IO
and File Management
Class Contents
Opening a file in ios::out mode also opens it in the ios::trunc mode by default.
Both ios::app and ios::ate take us to the end of the file when it opened. The difference between the two
parameters is that the ios::app allows us to add data to the end of file only, while ios::ate mode permits us
to add data or modify the existing data anywhere in the file. In both the cases, a file is created by the
specified name, if it does not exist.
Creating a stream using ifstream implies input and creating a stream using ofstream implies output. So, in
these cases it is not necessary to provide the mode parameters.
The mode can combine two or more parameters using the bitwise OR operator shown as follows.
Fout.open(“data”, ios::app | ios::nocreate);
This opens the file in the append mode but fails to open the file if it does not exist.
Each file has two pointers one is getpointer to input and second one is putpointer to output.
Functions for manipulation of file pointer
Functions Meaning
For example:
infile.seekg(20);
int p=fileout.tellp();
We can also pass two argument in the seekg() and seekp() functions as below.
seekg(offset, refposition);
seekp(offset, refposition);
The parameter offser represent the number of bytes the file pointer is to be moved from the location
specified by the parameter refposition.
Example:
#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
class emp
{
char name[30];
int ecode;
public:
emp()
{
}
void main()
{
emp e[4];
e[0]=emp(“amit”,1);
e[1]=emp(“joy”,2);
e[2]=emp(“rahul”,3);
e[3]=emp(“vikas”,4);
fstream file;
file.open(“empolyee.dat”, ios::in | ios::out);
int i;
for(i=0;i<4;i++)
file.write((char *) &e[i], sizeof(e[i]));
file.seekg(0, ios::end);
int end=file.tellg();
#include<iostream>
#include<fstream>
class inventory
{
char name[10];
int code;
float cost;
public:
void readdata();
void writedata();
};
void inventory::readdata()
{
cout<<"Enter name"<<endl;
cin>>name;
cout<<"Enter code"<<endl;
cin>>code;
cout<<"Enter price/cost"<<endl;
cin>>cost;
}
void inventory::writedata()
{
cout<<"Name ="<<name;
cout<<"Name ="<<code;
cout<<"Name ="<<cost;
}
int main()
{
inventory item[3];
fstream file;
file.open("stock.txt",ios::in |ios::out);
file.seekg(0);
cout<<"output";
for(int i=0;i<3;i++)
{
file.read((char *)&item[i],sizeof(item[i]));
item[i].writedata();
}
file.close();
return 0;
}
#include<iostream>
#include<fstream>
fstream f1,f2;
f1.open("abc.txt",ios::in);
f2.open("xyz.txt", ios::in);
char ch;
while(file)
{
f1.get(ch);
if(ch<65 || ch<90)
{
f2.put(ch);
}
return 0;
}
}
C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code
that behaves the same for any data type.
It can be considered as a kind of macro. When an object of a specific type is defined for actual use, the
template definition for that class is substituted with the required data type.
Function Template:
Suppose you write a function printData:
void printData(int value)
{
cout<<"The value is "<<value;
}
Now if you want to print double values or string values, then you have to overload the
function: void printData(float value)
{
cout<<"The value is "<<value;
}
void printData(char *value)
{
cout<<"The value is "<<*value;
}
To perform same operation with different data type, we have to write same code multiple
time. C++ provides templates to reduce this type of duplication of code.
template<typename T>
void printData(T value)
{
cout<<"The value is "<<value;
}
We can now use printData for any data type. Here T is a template parameter that identifies a type. Then,
anywhere in the function where T appears, it is replaced with whatever type the function is instantiated.
For example:
int i=3;
float d=4.75;
char *s="hello";
printData(i); // T is int
printData(d); // T is float
printData(s); // T is string
We can use more than one generic data type in the template statement, using comma seperated list as
shown below.
For example:
template <class T1, class T2>
void printData(T1 a, T2 b)
{
cout<<"\na="<<a<<"\tb="<<b;
}
int main()
{
printData(12,'N');
printData(12.5,34);
return 0;
}
2) Explain class template. Also write a C++ program for class template with multiple parameters.
Class Template:
It means we have to write same class two time because of only different data type.
}
void sum()
{
c=a+b;
}
void putdata()
{
cout<<"\nThe sum="<<c;
}
};
int main()
{
clrscr();
Sample <int> S1;
S1.getdata();
S1.sum();
S1.putdata();
Sample <float> S2;
S2.getdata();
S2.sum();
S2.putdata();
getch();
return 0;
}
We will pass data type when we create object of class. So, now template variable „T‟ is replace by data
type which we passed with object.
We can use more than one generic data type in a class template. They are declared as a comma
separated list within the template specification as shown below.
template <class T1, class T2>
class classname
{
/*Statement 1;
Statement 2;
.
.
Statement n; */
};
Example:
template<class T1, class T2>
class Sample
{
T1 a;
T2 b;
public:
Sample(T1 x,T2 y)
{
a=x;
b=y;
}
void disp()
{
cout<<"\na="<<a<<"\tb="<<b;
3) What is exception handling? Explain how to handle an exception with appropriate example. OR Explain how to
handle exceptions using try, catch and throw mechanism.
In programming two most common types of error are logical error and syntax error. The syntax error is
detected during compilation of program, but the logical error will detect during execution of program. So, it
is very difficult to handle logical error.
The exception handling provides mechanism to handle logical error during execution of
program. Steps to handle logical error:
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective actions (Handle the exception)
This mechanism is built upon three keyword: try, throw and catch.
A catch block is used to catches the exceptions thrown by throw statement and take appropriate
action. The relationship between try, throw and catch block is as shown in below figure.
try block
Detects and
throws an
exception
Exception
Object
catch block
Catches and
handles the
exception
Hardik Doshi, Ishan Rajani 62
Darshan Institute of Engineering & Technology 140705 – OOP with C++ Computer Engineering Unit - 8
Templates, Exceptions and STL
Syntax:
try
{
// Set of Statments;
throw exception;
// Set of Statements;
}
catch(type arg)
{
// Set of Statements;
}
Example:
#include <iostream>
using namespace std;
int main()
{
int a,b;
cout<<”Enter the value of a and b\n”;
cin>>a>>b;
try
{
if(b != 0)
cout<<”The result(a/b)=”<<a/b;
else
throw(b);
}
catch(int x)
{
cout<<”Exception caught b=”<<x;
}
return 0;
}
When the value of b is zero at that time exception will throw and this exception will catch in catch
block and print the message value is zero.
It is possible that a program segment has more than one condition to throw an exception. For
these situations we can associate more than one catch statement with a try block. When an
exception is thrown, the exception handlers are searched in order for an appropriate match. The fist
handler that yields a match is executed.
After executing the handler, the control goes to the first statement after the lat catch block for that
try. Note: It is possible that arguments of several catch statements match the type of an exception.
In such cases, the first handler that matches the exception type is executed.
Example:
#include<iostream>
using namespace std;
void test(int x)
{
try
{
if(x==1)
{
throw(x);
}
else if(x==0)
{
throw 'x';
}
else if(x==-1)
{
throw 1.0;
}
}
catch(char c)
{
cout<<"Caught a character"<<endl;
}
catch(int m)
{
cout<<"Caught an integer"<<endl;
}
catch(float n)
{
cout<<"Caught a double"<<endl;
}
cout<<"End of the try catch system"<<endl;
}
int main()
{
cout<<"Testing multiple catch"<<endl;
cout<<"x==1"<<endl;
test(1);
cout<<"x==0"<<endl;
test(0);
cout<<"x==-1"<<endl;
test(-1);
cout<<"x==2"<<endl;
test(2);
return 0;
}
A handler may decide to rethrow the exception caught without processing it.
In such situations, we may simply invoke throw without any arguments as shown below:
throw;
This causes the current exception to be thrown to the next enclosing try/catch sequence and is caught by
a catch statement listed after that enclosing try block.
Example:
#include<iostream>
using namespace std;
{
cout<<"Inside function \n";
try
{
if (y==0)
throw y;
else
cout<<"Division ="<<x/y<<"\n";
}
catch(double)
{
cout<<"caught double inside the function \n";
throw;
}
cout<<"End of function \n\n";
}
int main()
{
cout<<"Inside main";
try
{
divide(10.5,2.5);
divide(4,0);
}
catch(double)
{
cout<<"caught double inside main \n";
}
cout<<"End of main\n";
return 0;
}
Alexander Stepanov and Meng Lee of Hewlett-jPackard developed a set of general-purpose templatized
classes and function for storing and processing of data.
The collection of these generic classes is called Standard Template Library(STL). The
STL has now become a part of the ANSI standard C++ library.
Using STL, we can save considerable time and effort, and lead to high quality programs. All these
benefits are possible because we are basically “reusing” the well-written and well-tested components
defined in the STL.
STL components which are now part of the standard C++ library are defined in the namespace std.
We must therefore using namespace directive, to intend to use the Standard C++ library. using
namespace std;
These three components work in conjunction with one another to provide support to a variety of
programming solution.
Container
Algorithm 1 Algorithm 2
Iterator 1 Iterator 2
Object 1 Object 2
Object 3
Iterator 3
Algorithm 3
Container:
The STL containers are implemented by template classes and therefore can be easily customized to hold
different types of data.
Algorithm:
An algorithm is a procedure that is used to process the data contained in the containers. The STL
includes many different kinds of algorithms to provide support to taks such as initializing, searching,
copying, sorting, and merging.
Iterator:
Iterators connect algorithms with containers and play a key role in the manipulation of data stored in
the containers