Professional Documents
Culture Documents
Tirup Parmar
Video
MumbaiLectures @ https://www.youtube.com/c/TirupParmar
University Page 1
Course Code: USIT201
Prof. Tirup Parmar
Syllabus
Unit Details
1 Object Oriented Methodology:
Introduction, Advantages and Disadvantages of Procedure Oriented Languages, what is
Object Oriented? What is Object Oriented Development? Object Oriented Themes,
Benefits and Application of OOPS.
Principles of OOPS: OOPS Paradigm, Basic Concepts of OOPS: Objects, Classes, Data
Abstraction and Data Encapsulation, Inheritance, Polymorphism, Dynamic Binding,
Message Passing
2 Classes and Objects: Simple classes (Class specification, class members accessing),
Defining member functions, passing object as an argument, Returning object from
functions, friend classes, Pointer to object, Array of pointer to object.
Constructors and Destructors: Introduction, Default Constructor, Parameterized
Constructor and examples, Destructors
UNIT I
Object Oriented Methodology
Introduction
A Brief Programming History
Computer Programming
The history of computer programming is a steady move away from machine-oriented views of
programming towards concepts and metaphors that more closely reflect the way in which we
ourselves see & understand the world
Programming Languages
Machine Languages
• Comprised of 1s and 0s
• The “native” language of a computer
• Difficult to program – one misplaced 1 or 0 will cause the program to fail.
• Example of code:
1110100010101 111010101110
10111010110100 10100011110111
Assembly Languages
• Assembly language code needs to be translated to machine language before the computer
processes it.
• Example:
High-Level Languages
• High-level languages represent a giant leap towards easier programming.
• The syntax of HL languages is similar to English.
• Example:
grossPay = basePay + overTimePay
• Interpreter – Executes high level language programs without compilation.
• Historically, we divide HL languages into two groups:
– Procedural languages
Procedural Languages
• Early high-level languages are typically called procedural languages.
• Procedural languages are characterized by sequential sets of linear commands. The focus of
such languages is on structure.
• Examples include C, COBOL, Fortran, LISP, Perl, HTML, VBScript
Object-Oriented Languages
PPL involves coding instructions that a computer execute in a particular order . the
language makes it easy to debug different procedures in isolation.
It is also easy to read the code hence making it easy to change a particular procedure.
Easy location of error in program
Easy understanding of program code.
Execution of program is faster.
Procedural languages are easier to learn and use.
Procedural languages executes quickly.
Procedural languages reduce amount of overhead during runtime.
Disadvantages
1. Complex coding
2. No security due to use of pointers
3. gives more importance to instruction than data
4. For global variables declared program becomes junky.
5. the need to change larger portion of the code during porting and inability to use
the original code on a different application.
6. not easy to maintain.
programs uses constructs such as if-else, for-loop, array, function, pointer, which are low-
level and hard to abstract real problems such as a Customer Relationship Management
(CRM) system or a computer soccer game. (Imagine using assembly codes, which is a
very low level code, to write a computer soccer game. C is better but no much better.)
It emphasis on doing things. Data is given a second class status even through data is the
reason for the existence of the program.
Since every function has complete access to the global variables, the new programmer
can corrupt the data accidentally by creating function. Similarly, if new data is to be
added, all the function needed to be modified to access the data.
It is often difficult to design because the components function and data structure do not
model the real world.
Complex coding
No security due to use of pointers
gives more importance to instruction than data
For global variables declared program becomes junky.
the need to change larger portion of the code during porting and inability to use the original
code on a different application.
not easy to maintain.
For example, in designing graphics user interface, we think what functions, what data structures
are needed rather than which menu, menu item and soon.
It is difficult to create new data types. The ability to create the new data type of its own is
called extensibility. Structured programming languages are not extensible.
The organization of data and functions is object oriented program is shown in fig.
As an example, suppose you wish to write a computer soccer games (which I consider as a
complex application). It is quite difficult to model the game in procedural-oriented languages.
But using OOP languages, you can easily model the program accordingly to the "real things"
appear in the soccer games.
Player: attributes include name, number, location in the field, and etc; operations include
run, jump, kick-the-ball, and etc.
Ball:
Reference:
Field:
Audience:
Weather:
Most importantly, some of these classes (such as Ball and Audience) can be reused in another
application, e.g., computer basketball game, with little or no modification.
An Object-Oriented Class
If we think of a real-world object, such as a television (as in Figure 1.1), it will have several
features and properties:
A class should:
With a functional programming language (like C) we would have the component parts of the
television scattered everywhere and we would be responsible for making them work correctly -
there would be no case surrounding the electronic components.
Humans use class based descriptions all the time - what is a duck? (Think about this, we will
discuss it soon.)
Classes allow us a way to represent complex structures within a programming language. They have
two components:
States - (or data) are the values that the object has.
Methods - (or behaviour) are the ways in which the object can interact with its data, the
actions.
The notation used in Figure 1.2 on the right hand side is a Unified Modelling Language (UML)
representation of the Television class for object-oriented modelling and programming.
An Object
An object is an instance of a class. You could think of a class as the description of a concept, and
an object as the realisation of this description to create an independent distinguishable entity. For
example, in the case of the Television, the class is the set of plans (or blueprints) for a generic
television, whereas a television object is the realisation of these plans into a real-world physical
television. So there would be one set of plans (the class), but there could be thousands of real-
world televisions (objects).
Objects can be concrete (a real-world object, a file on a computer) or could be conceptual (such as
a database structure) each with its own individual identity. Figure 1.3 shows an example where
the Television class description is realised into several television objects. These objects should
have their own identity and are independent from each other. For example, if the channel is
changed on one television it will not change on the other televisions.
Encapsulation
You can think of this in the case of the Television class, where the functionality of the television
is hidden from us, but we are provided with a remote control, or set of controls for interacting with
the television, providing a high level of abstraction. So, as in Figure 1.4 there is no requirement to
understand how the signal is decoded from the aerial and converted into a picture to be displayed
on the screen before you can use the television.
There is a sub-set of functionality that the user is allowed to call, termed the interface. In the case
of the television, this would be the functionality that we could use through the remote control or
buttons on the front of the television.
The full implemenation of a class is the sum of the public interface plus the private implementation.
Encapsulation is the term used to describe the way that the interface is separated from the
implementation. You can think of encapsulation as "data-hiding", allowing certain parts of an
object to be visible, while other parts remain hidden. This has advantages for both the user and the
programmer.
The programmer can change the implementation, but need not notify the user.
So, providing the programmer does not change the interface in any way, the user will be unaware
of any changes, except maybe a minor change in the actual functionality of the application.
We can identify a level of 'hiding' of particular methods or states within a class using
the public, private and protected keywords:
Figure 1.5 shows encapsulation as it relates to the Television class. According to UML notation
private methods are denoted with a minus sign and public methods are denoted with a plus sign.
The private methods would be methods written that are part of the inner workings of the television,
but need not be understood by the user. For example, the user would need to call the
powerOn() method but the private displayPicture() method would also be called, but internally
as required, not directly by the user. This method is therefore not added to the interface, but hidden
internally in the implementation by using the private keyword.
Inheritance
If we have several descriptions with some commonality between these descriptions, we can group
the descriptions and their commonality using inheritance to provide a compact representation of
these descriptions. The object-oriented programming approach allows us to group the
commonalities and create classes that can describe their differences from other classes.
Humans use this concept in categorising objects and descriptions. For example you may have
answered the question - "What is a duck?", with "a bird that swims", or even more accurately, "a
bird that swims, with webbed feet, and a bill instead of a beak". So we could say that a Duck is a
Bird that swims, so we could describe this as in Figure 1.6. This figure illustrates the inheritance
relationship between a Duck and a Bird. In effect we can say that a Duck is a special type
of Bird.
For example: if were to be given an unstructured group of descriptions such as Car, Saloon, Estate,
Van, Vehicle, Motorbike and Scooter, and asked to organise these descriptions by their differences.
You might say that a Saloon car is a Car but has a long boot, whereas an Estate car is a car with a
very large boot. Figure 1.7 shows an example of how we may organise these descriptions using
inheritance.
So we can describe this relationship as a child/parent relationship, where Figure 1.8 illustrates the
relationship between a base class and a derived class. A derived class inherits from a base class,
so in Figure 1.7 the Car class is a child of the Vehicle class, so Car inherits from Vehicle.
One way to determine that you have organised your classes correctly is to check them using
the "IS-A" and "IS-A-PART-OF" relationship checks. It is easy to confuse objects within a class
and children of classes when you first begin programming with an OOP methodology. So, to check
the previous relationship between Car and Vehicle, we can see this in Figure 1.9.
The IS-A relationship describes the inheritance in the figure, where we can say, "A Car IS-A
Vehicle" and "A SaloonCar IS-A Car", so all relationships are correct. The IS-A-PART-OF
relationship describes the composition (or aggregation) of a class. So in the same figure (Figure
1.9) we can say "An Engine IS-A-PART-OF a Vehicle", or "An Engine, Colour and Wheels IS-
A-PART-OF a Vehicle". This is the case even though an Engine is also a class! where there could
be many different descriptions of an Engine - petrol, diesel, 1.4, 2.0, 16 valve etc.
Inherit a behaviour and add further specialised behaviour - for example a Car IS A
Vehicle with the addition of four Wheel objects, Seats etc.
Inherit a behaviour and replace it - for example the SaloonCar class will inherit from
Car and provide a new "boot" implementation.
Cut down on the amount of code that needs to be written and debugged - for example in
this case only the differences are detailed, a SaloonCar is essentially identical to the
Car, with only the differences requiring description.
Polymorphism
When a class inherits from another class it inherits both the states and methods of that class, so in
the case of the Car class inheriting from the Vehicle class the Car class inherits the methods
of the Vehicle class, such as engineStart(), gearChange(), lightsOn() etc. The Car class
will also inherit the states of the Vehicle class, such as isEngineOn, isLightsOn,
numberWheels etc.
Polymorphism means "multiple forms". In OOP these multiple forms refer to multiple forms of
the same method, where the exact same method name can be used in different classes, or the same
method name can be used in the same class with slightly different paramaters. There are two forms
of polymorphism, over-riding and over-loading.
Over-Riding
As discussed, a derived class inherits its methods from the base class. It may be necessary to
redefine an inherited method to provide specific behaviour for a derived class - and so alter the
implementation. So, over-riding is the term used to describe the situation where the same method
name is called on two different objects and each object responds differently.
Over-riding allows different kinds of objects that share a common behaviour to be used in code
that only requires that common behaviour.
Consider the previous example of the Vehicle class diagram in Figure 1.7. In this case
Car inherits from Vehicle and from this class Car there are further derived classes
SaloonCar and EstateCar. If a draw()method is added to the Car class, that is required to
draw a picture of a generic vehicle. This method will not adequately draw an estate car, or other
child classes. Over-Riding allows us to write a specialised draw() method for the
EstateCar class - There is no need to write a new draw() method for the SaloonCar class as
the Car class provides a suitable enough draw() method. All we have to do is write a new
draw() method in the EstateCar class with the exact same method name. So, Over-Riding
allows:
A more straightforward API where we can call methods the same name, even thought these
methods have slightly different functionality.
A better level of abstraction, in that the implementation mechanics remain hidden.
Over-Loading
Over-Loading is the second form of polymorphism. The same method name can be used, but the
number of parameters or the types of parameters can differ, allowing the correct method to be
chosen by the compiler. For example:
are two different methods that have the same name and the same number of parameters. However,
when we pass two String objects instead of two int variables then we expect different
functionality. When we add two int values we expect an intresult - for example 6 + 7 = 13.
However, if we passed two String objects we would expect a result of "6" + "7" = "67". In other
words the strings should be concatenated.
The number of arguments can also determine which method should be run. For example:
channel()
channel(int x)
will provide different functionality where the first method may simply display the current channel
number, but the second method will set the channel number to the number passed.
Q-3) Explain dynamic binding with example. Give proper example. (2017)
Dynamic Binding: In dynamic binding, the code to be executed in response to function call
is decided at runtime. C++ has virtual functions to support this.
Virtual functions allow us to create a list of base class pointers and call methods of any of the
derived classes without even knowing kind of derived class object. For example, consider a
employee management software for an organization, let the code has a simple base
class Employee , the class contains virtual functions like raiseSalary(), transfer(), promote(),.. etc.
Different types of employees like Manager, Engineer, ..etc may have their own implementations
of the virtual functions present in base class Employee. In our complete software, we just need to
pass a list of employees everywhere and call appropriate functions without even knowing the type
of employee. For example, we can easily raise salary of all employees by iterating through list of
employees. Every type of employee may have its own logic in its class, we don’t need to worry
because if raiseSalary()is present for a specific employee type, only that function would be called.
class Employee
{
public:
Message Passing: Objects communicate with one another by sending and receiving
information to each other. A message for an object is a request for execution of a procedure and
therefore will invoke a function in the receiving object that generates the desired results. Message
passing involves specifying the name of the object, the name of the function and the information
to be sent.
5. OOA organizes results based upon problem domain constructs, for present reuse and future
reuse.
6. Software complexity can be easily managed.
Q-5) Write a short note on Data abstraction and data encapsulation. (2017)
Abstraction: - abstraction refers to the act of representing essential features without including
the explanations. Classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, cost and functions to operate on these attributes. They encapsulate all the
essential properties of the objects that are to be created. The functions that operate on these data
are called as methods or member functions.
Data Access In POP, Most function uses Global In OOP, data can not move easily
data for sharing that can be accessed from function to function,it can be
freely from function to function in kept public or private so we can
the system. control the access of data.
Data Hiding POP does not have any proper way OOP provides Data Hiding so
for hiding data so it is less secure. 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, Example of OOP are : C++, JAVA,
FORTRAN, Pascal. VB.NET, C#.NET.
Datatype in C++
Data type is a keyword used to identify type of data. It is used for storing the input of the
program into the main memory (RAM) of the computer by allocating sufficient amount of
memory space in the main memory of the computer.
In general every programming language is containing three categories of data types. They are
These are the data types whose variable can hold maximum one value at a time, in C++
language it can be achieve by int, float, double, char.
Example
int a; // valid
a = 10,20,30; // invalid
These data type are derived from fundamental data type. Variables of derived data type allow
us to store multiple values of same type in one variable but never allows to store multiple values
of different types. These are the data type whose variable can hold more than one value of
similar type. In C++ language it can be achieve by array.
Example
User defined data types related variables allows us to store multiple values either of same type
or different type or both. This is a data type whose variable can hold more than one value of
dissimilar type, in C++ language it is achieved by structure.
Syntax
struct emp
{
int id;
char ename[10];
float sal;
};
In C++ language, user defined data types can be developed by using struct, union, enum etc.
In C++ language Data Type Modifiers are keywords used to change the properties of current
properties of data type. Datatype modifiers are classified into following types.
long
short
unsigned
signed
Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount
of storage space allocated to a variable.
For example, storage space for int data type is 4 byte for 32 bit processor. We can increase the
range by using long int which is 8 byte. We can decrease the range by using short int which is
2 byte.
long:
This can be used to increased size of the current data type to 2 more bytes, which can be applied
on int or double data types. For example int occupy 2 byte of memory if we use long with
integer variable then it occupy 4 byte of memory.
Syntax
short
In general int data type occupies different memory spaces for a different operating system; to
allocate fixed memory space short keyword can be used.
Syntax
short int a; --> occupies 2 bytes of memory space in every operating system.
unsigned
This keyword can be used to make the accepting values of a data type is positive data type.
Syntax
Signed
This keyword accepts both negative or positive value and this is default properties or data type
modifiers for every data type.
Example
Note: in real time no need to write signed keyword explicitly for any data type.
Variable in C++
Variable is an identifier which holds data or another one variable is an identifier whose value
can be changed at the execution time of program. Variable is an identifier which can be used to
identify input data in a program.
Syntax
Variable_name = value;
Variable declarations
This is the process of allocating sufficient memory space for the data in term of variable.
Syntax
Datatype variable_name; int a;
If no input values are assigned by the user than system will gives a default value called garbage
value.
Garbage value
Garbage value can be any value given by system and that is no way related to correct programs.
It is a disadvantage and it can overcome using variable initialization.
Variable initialization
It is the process of allocating sufficient memory space with user defined values.
Syntax
Datatype nariable_name=value;
Example
int b = 30;
Variable assignment
Syntax
Variable_Name = value
Example
int a= 20;
int b;
Example
To Declare any variable in C++ you need to follow rules and regulation of C++ Language,
which is given below;
Every variable name always should exist in the left hand side of assignment operator.
Variable declarations
This is the process of allocating sufficient memory space for the data in term of variable.
Syntax
Datatype variable_name;
int a;
If no input values are assigned by the user than system will gives a default value called garbage
value.
Global variable
Global variables are defined outside of all the functions, generally on top of the program. The
global variables will hold their value throughout the life-time of your program.
Local variable
A local variable is declared within the body of a function or a block. Local variable only use
within the function or block where it is declare.
#include<iostream.h>
#include<conio.h>
cout<<"Value of a: "<<a;
cout<<"Value of b: "<<b;
getch();
}
Output
Value of a: 10
Value of b: 20
Operators in C++
Operator is a special symbol that tells the compiler to perform specific mathematical or logical
Operation.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Arithmetic Operators
Given table shows all the Arithmetic operator supported by C Language. Lets suppose
variable A hold 8 and B hold 3.
Operator Example (int A=8, B=3) Result
+ A+B 11
- A-B 5
* A*B 24
/ A/B 2
% A%4 0
Relational Operators
Which can be used to check the Condition, it always return true or false. Lets suppose
variable A hold 8 and B hold 3.
Operators Example (int A=8, B=3) Result
== A== B False
!= A!=(-4) True
Logical Operator
Which can be used to combine more than one Condition?. Suppose you want to combined two
conditions A<B and B>C, then you need to use Logical Operator like (A<B) && (B>C).
Here && is Logical Operator.
Operator Example (int A=8, B=3, C=-10) Result
! !(B<=-A) True
T T T T F F
T F F T F T
F T F T T F
F F F F T T
Assignment operators
Which can be used to assign a value to a variable. Lets suppose variable A hold 8 and B hold
3.
Operator Example (int A=8, B=3) Result
+= A+=B or A=A+B 11
-= A-=3 or A=A+3 5
*= A*=7 or A=A*7 56
/= A/=B or A=A/B 2
%= A%=5 or A=A%5 3
For writing C++ code you need turbo c editor and write code after writing code save the code
with .cpp extension, compile the code and finally run the program.
Example
#include<iostream.h>
#include<conio.h>
void main()
{
cout<<"This is my first program";
getch();
}
Output
Save C program
Save any C++ program using .cpp Extension with file name. For example your program name
is sum, then it save with sum.cpp.
Syntax
filename.cpp
For compile any C++ program you just press alt+f9 , after compilation of your C++ program
you press clt+f9 for run your C++ program.
Syntax
Priority:
Associativity:
It represents which operator should be evaluated first if an expression is containing more than
one operator with same priority.
*, /, % 3 Left to right
+, - 4 Left to right
|| 7 Left to right
?: 8 Right to left
Example 1: Example 2:
Error is a abnormal condition whenever it occurs execution of the program is stopped these
are mainly classified into following types.
If any error is generated at the time of compilation is known as compile time error, in general
these are raised while break down the rules and regulation of programming language. Compile
time errors also known as syntax errors.
If any error is generated at run time is known as runtime error, in general these are raised
because of writing wrong logics in the program.
Example
Int a=10,b;
In general it is very difficult to identify logical error in C language, to overcome this problem
exception handling was introduced in object oriented programming language.
Warning
Warning is also an abnormal condition but whenever it occurred execution of program will
never be stopped.
Note: In C language warning can be neglected but error can not be neglected.
Syntax
class class_name
{
data members;
user defined method;
{
..........
..........
}
};
Include section
# include is a pre-processor directive can be used to include all the predefined method of given
header files into current C program before compilation.
Syntax
#include<headerfile.h>
class
Class is a blue print which is containing only list of variables and method.
C++ library is collection of header files, header files is a container which is collection of related
predefined method.
If any method is defined by the user is known as user defined method. Method is collection of
statement used to perform a specific Operation.
Syntax
returntype method_name()
.......
.......
In the above syntax method name can be any user defined name, return type represents which
type of value it can return to its calling method.
Syntax
Main() method
This is starting executable block of any program (it is always executed by processor and OS ).
One C++ program can have maximum one main() the entire statements of given program can
be executed through main(). Without main() method no C++ program will be executed.
Syntax
returntype main()
......
.....
If return type is void that method can not return any value to the operating system. So that void
can be treated as no return type.
Example
#include<iostream.h>
#include<conio.h>
void main()
{
cout<<("Hello main";
}
Output
Hello main
IO statements in C++
IO represents input output statements, and input statement can be used to read the input value
from the standard input device (keyboard), output statement can be used to display the output
in standard output device (Monitor) respectively. In C++ language IO statement can be achieve
by using cout<< and >>cin.
#include<iostream.h>
#include<conio.h>
void main()
{
int num;
clrscr();
cout<<"Hello word !"; // print message on screen
getch();
}
Output
Hello word !
cin
#include<iostream.h>
#include<conio.h>
void main()
{
int num;
clrscr();
cout<<"Enter any number:";
cin>>num; // accept one value form keyboard
cout<<"Number is: "<<num;
gech();
}
Output
main() function is the entry point of any C++ program. It is the point at which execution of
program is started. When a C++ program is executed, the execution control goes directly to the
main() function. Every C++ program have a main() function.
Syntax
void main()
{
............
............
}
In above syntax;
void: is a keyword in C++ language, void means nothing, whenever we use void as a
function return type then that function nothing return. here main() function no return any
value.
In place of void we can also use int return type of main() function, at that time main()
return integer type value.
main: is a name of function which is predefined function in C++ library.
Example
#include<stdio.h>
void main()
{
cout<<"This is main function";
}
Output
clrscr() and getch() both are predefined function in "conio.h" (console input output header file).
Clrscr()
It is a predefined function in "conio.h" (console input output header file) used to clear the
console screen. It is a predefined function, by using this function we can clear the data from
console (Monitor). Using of clrscr() is always optional but it should be place after variable or
function declaration only.
Example of clrscr()
#include<iostream.h>
#include<conio.h>
void main()
{
int a=10, b=20;
int sum=0;
clrscr(); // use clrscr() after variable declaration
sum=a+b;
cout<<"Sum: "<<sum;
getch();
Output
Sum: 30
Getch()
It is a predefined function in "conio.h" (console input output header file) will tell to the console
wait for some time until a key is hit given after running of program.
By using this function we can read a character directly from the keyboard. Generally getch()
are placing at end of the program after printing the output on screen.
Example of getch()
#include<iostream.h>
#include<conio.h>
void main()
{
int a=10, b=20;
int sum=0;
clrscr();
sum=a+b;
cout<<"Sum: "<<sum;
getch(); // use getch() befor end of main()
}
Output
Sum: 30
Decision making statement is depending on the condition block need to be executed or not
which is decided by condition.
If the condition is "true" statement block will be executed, if condition is "false" then statement
block will not be executed.
In this section we are discuss about if-then (if), if-then-else (if else), and switch statement. In
C++ language there are three types of decision making statement.
if
if-else
switch
if-then Statement
if-then is most basic statement of Decision making statement. It tells to program to execute a
certain part of code only if particular condition is true.
Syntax
If(condition)
..........
..........
Constructing the body of "if" statement is always optional, Create the body when we are
having multiple statements.
If the body is not specified, then automatically condition part will be terminated with next
semicolon ( ; ).
else
It is a keyword, by using this keyword we can create a alternative block for "if" part. Using else
is always optional i.e, it is recommended to use when we are having alternate block of condition.
In any program among if and else only one block will be executed. When if condition is false
then else part will be executed, if part is executed then automatically else part will be ignored.
if-else statement
In general it can be used to execute one block of statement among two blocks, in C language if
and else are the keyword in C.
Syntax
if(condition)
........
statements
........
else
........
statements
........
In the above syntax whenever condition is true all the if block statement are executed remaining
statement of the program by neglecting else block statement. If the condition is false else block
statement remaining statement of the program are executed by neglecting if block statements.
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int time=10;
clrscr();
if(time>12)
{
cout<<"Good morning";
}
{
cout<<"Good after noon";
}
getch();
}
Output
Good morning
Switch Statement
A switch statement work with byte, short, char and int primitive data type, it also works with
enumerated types and string.
Syntax
switch(expression/variable)
case value:
//statements
break; //optional
default: //optional
//statements
1. With switch statement use only byte, short, int, char data type.
2. You can use any number of case statements within a switch.
3. Value for a case must be same as the variable in switch .
Limitations of switch
Example
Switch case variables can have only int and char data type. So float data type is not allowed.
Syntax
switch(ch)
case1:
statement 1;
break;
case2:
statement 2;
break;
In this ch can be integer or char and cannot be float or any other data type.
#include<iostream.h>
#include<conio.h>
void main()
{
int ch;
clrscr();
cout<<"Enter any number (1 to 7)";
cin>>ch;
switch(ch)
{
case 1:
cout<<"Today is Monday";
break;
case 2:
cout<<"Today is Tuesday";
break;
case 3:
cout<<"Today is Wednesday";
break;
case 4:
cout<<"Today is Thursday";
break;
case 5:
cout<<"Today is Friday";
break;
case 6:
cout<<"Today is Saturday";
break;
case 7:
cout<<"Today is Sunday";
break;
default:
cout<<"Only enter value 1 to 7";
}
getch();
}
Output
Today is Friday
Note: In switch statement default is optional but when we use this in switch default is executed
In while loop First check the condition if condition is true then control goes inside the loop
body other wise goes outside the body. while loop will be repeats in clock wise direction.
Syntax
Assignment;
while(condition)
{
statements;
............
Increment or Decrements (++ or --);
}
Note: If while loop condition never false then loop become infinite loop.
When while loop is use ?
When we do not know about how many times loops are perform or iteration of loop is unknown.
Flow Diagram
#include<iostream.h>
#include<conio.h>
void main()
{
int i;
clrscr();
i=1;
while(i<5)
{
cout<<endl<<i;
i++;
}
getch();
}
Output
Output:
When you need to execute a block of code several number of times then you need to use looping
concept in C++ language. In C++ Programming Language for loop is a statement which allows
code to be repeatedly executed. For loop contains 3 parts.
Initialization
Condition
Increment or Decrements
Syntax
Initialization: step is execute first and this is execute only once when we are entering into
the loop first time. This step is allow to declare and initialize any loop control variables.
Condition: is next step after initialization step, if it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and flow of control goes
outside the for loop.
Increment or Decrements: After completion of Initialization and Condition steps loop
body code is executed and then Increment or Decrements steps is execute. This statement
allows to update any loop control variables.
Note: In for loop everything is optional but mandatory to place 2 semicolons (; ;)
Example
for() // Error
for( ; ; ) // valid
Flow Diagram
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=1;i<5;i++)
{
cout<<endl<<i;
}
getch();
}
Output
1
2
3
4
Important Points
1. In for loop if condition part is not given then it will repeats infinite times, because
condition part will replace it non-zero. So it is always true like.
for( ; 1; )
2. For loop is repeats in anti lock wise direction.
3. In for loop also rechecking process will be occurred that is before execution of the
statement block, condition part will evaluated.
Example
while(0)// no repetition
for( ; 0; ) // it will repeats 1 time
Note: Always execution process of for loop is faster than while loop.
do-while in C++
A do-while loop is similar to a while loop, except that a do-while loop is execute at least one
time.
A do while loop is a control flow statement that executes a block of code at least once, and then
repeatedly executes the block, or not, depending on a given condition at the end of the block
(in while).
Syntax
do
{
Statements;
........
Increment or Decrements (++ or --)
}
while(condition);
Flow Diagram
When you need to executes a block of code at least once, at that time do-while loop is use.
#include<iostream.h>
#include<conio.h>
void main()
{
int i;
clrscr();
i=1;
do
{
cout<<endl<<i;
i++;
}
while(i<5);
getch();
}
Output
1
2
3
4
UNIT II
Class and Object in C++
Object is the physical as well as logical entity where as class is the only logical entity.
Class: Class is a blue print which is containing only list of variables and method and no
memory is allocated for them. A class is a group of objects that has common properties.
Data Member
Method
Constructor
Block
State
Behavior
Identity
Syntax
class_name object_reference;
Example
Employee e;
Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw etc.
Identity: Object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But,it is used internally by the JVM to identify each object uniquely.
In real world many examples of object and class like dog, cat, and cow are belong to animal's
class. Each object has state and behaviors. For example a dog has state:- color, name, height,
Vehicle class
Car, bike, truck these all are belongs to vehicle class. These Objects have also different
different states and behaviors. For Example car has state - color, name, model, speed, Mileage.
Class Object
One class definition should exist only For one class multiple objects can be
3
once in the program. created.
class Class_Name
data member;
method;
In this example, we have created a Employee class that have two data members eid and
ename. We are creating the object of the Employee class and printing the objects value.
Example
#include<iostream.h>
#include<conio.h>
class Employee
{
public:
int salary // data member
void sal()
{
cout<<"Enter salary: ";
cin>>salary;
cout<<"Salary: "<<salary;
}
};
void main()
{
clrscr();
Employee e; //creating an object of Employee
e.sal();
getch();
}
Output
Salary: 4500
Access specifiers in C++ define how the members of the class can be accessed. C++ has 3 new
keywords introduced, namely.
public
private
protected
The keywords public, private, and protected are called access specifiers. A class can have
multiple public, protected, or private labeled sections.
Note: By default, all members and function of a class is private i.e if no access specifier is
specified.
class
private:
public:
protected:
};
Public class members are accessible out side the class and it is available for every one.
Syntax
class Public_Access_Specifier
Private class members are accessible with the class and it is not accessible out side the class. If
some one try to access out side the it gives compile time error. By default class variables and
member functions are private.
Syntax
class Private_Access_Specifier
#include<iostream.h>
#include<conio.h>
class A
{
private:
int a;
public:
int b;
public:
void show()
{
a=10 ;
b=20;
clrscr();
//Every members can be access here, same class
cout<<"\nAccessing variable within the class"<<endl;
cout<<"Value of a: "<<a<<endl;
cout<<"Value of b: "<<b<<endl;
}
};
void main()
{
A obj; // create object
obj.show();
cout<<"\nAccessing variable outside the class"<<endl;
//'a' cannot be accessed as it is private
//cout<<"value of a: "<<obj.a<<endl;
Note: If here, we access variable a in side main method it will give compile time error
Output
It is similar to private access specifier. It makes class member inaccessible outside the class.
But they can be accessed by any subclass of that class.
Syntax
class Protected_Access_Specifier
{
protected: // protected access specifier
int a; // Data Member Declaration
void display(); // Member Function Declaration
}
In below example I will show you all these access specifier public, private and protected.
#include<iostream.h>
#include<conio.h>
class Declaration
{
private:
int a;
public:
int b;
protected:
int c;
public:
void show()
{
a=10;
b=20;
c=30;
//Every members can be access here, same class
cout<<"\nAccessing variable within the class"<<endl;
cout<<"Value of a: "<<a<<endl;
cout<<"Value of b: "<<b<<endl;
cout<<"Value of c: "<<c<<endl;
}
};
//cout<<"Value of a: "<<a<<endl;
//b is public so it is accessible any where
cout<<"Value of b: "<<b<<endl;
//'c' is declared as protected, so it is accessible in sub class
cout<<"Value of c: "<<c<<endl;
}
};
void main()
{
clrscr();
Declaration d; // create object
d.show();
Output
value of a: 10
value of b: 20
value of c: 30
value of b: 5
value of c: 6
Value of b: 20
Function in C++
A function is a group of statements that together perform a specific task. Every C++ program
has at least one function, which is main().
Function are used for divide a large code into module, due to this we can easily debug and
maintain the code. For example if we write a calculator programs at that time we can write
every logic in a separate function (For addition sum(), for subtraction sub()). Any function can
be called many times.
Advantage of Function
Code Re-usability
Type of Function
Library function
Library functions are those which are predefined in C++ compiler. The implementation part of
pre-defined functions is available in library files that are .lib/.obj files. .lib or .obj files are
contained pre-compiled code. printf(), scanf(), clrscr(), pow() etc. are pre-defined functions.
All predefined function are contained limited task only that is for what purpose function is
designed for same purpose it should be used.
These functions are created by programmer according to their requirement for example suppose
you want to create a function for add two number then you create a function with name sum()
this type of function is called user defined function.
Defining a function.
Defining of function is nothing but give body of function that means write logic inside function
body.
Syntax
return_type function_name(parameter)
function body;
Return type: A function may return a value. The return_type is the data type of the value
the function returns.Return type parameters and returns statement are optional.
Function name: Function name is the name of function it is decided by programmer or
you.
Parameters: This is a value which is pass in function at the time of calling of function A
parameter is like a placeholder. It is optional.
Function body: Function body is the collection of statements.
Function Declarations
A function declaration is the process of tells the compiler about a function name. The actual
body of the function can be defined separately.
Syntax
return_type function_name(parameter);
Note: At the time of function declaration function must be terminated with ';'.
calling a function.
When we call any function control goes to function body and execute entire code. For call any
function just write name of function and if any parameter is required then pass parameter.
Syntax
function_name();
or
variable=function_name(argument);
Note: At the time of function calling function must be terminated with ';'.
#include<iostream.h>
#include<conio.h>
Output
Sum: 30
If a function take any arguments, it must declare variables that accept the values as a arguments.
These variables are called the formal parameters of the function. There are two ways to pass
value or data to function in C++ language which is given below;
call by value
call by reference
Call by value
In call by value, original value can not be changed or modified. In call by value, when you
passed value to the function it is locally stored by the function parameter in stack memory
location. If you change the value of function parameter, it is changed for the current function
only but it not change the value of variable inside the caller function such as main().
Program Call by value in C++
#include<iostream.h>
#include<conio.h>
void swap(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
void main()
{
int a=100, b=200;
clrscr();
swap(a, b); // passing value to function
cout<<"Value of a"<<a;
cout<<"Value of b"<<b;
getch();
}
Output
Value of a: 200
Value of b: 100
Call by reference
#include<iostream.h>
#include<conio.h>
Output
Value of a: 200
Value of b: 100
This method copy original value into This method copy address of arguments into
function as a arguments. function as a arguments.
Actual and formal arguments will be Actual and formal arguments will be created in
created in different memory location same memory location
To pass the value by pointer, argument pointers are passed to the functions just like any other
value. So accordingly you need to declare the function parameters as pointer types as in the
following function swap(), which exchanges the values of the two integer variables pointed to by
its arguments.
int temp;
return;
For now, let us call the function swap() by passing values by pointer as in the following example
−
#include <iostream>
// function declaration
int main () {
int a = 100;
int b = 200;
*/
swap(&a, &b);
return 0;
When the above code is put together in a file, compiled and executed, it
produces the following result −
Before swap, value of a :100
Before swap, value of b :200
Q-1) What is friend function? Write a friend function to display mark sheet of
the F. Y. B. Sc. IT student. (April 2017)
In C++ a Friend Function that is a "friend" of a given class is allowed access to private and
protected data in that class.
A function can be made a friend function using keyword friend. Any friend function is preceded
with friend keyword. The declaration of friend function should be made inside the body of
class (can be anywhere inside class either in private or public section) starting with keyword
friend.
You do not access private or protected data member of any class, to access private and protected
data member of any class you need a friend function.
Syntax
class class_name
{
......
friend returntype function_name(arguments); }
Friend class
Similarly like, friend function a class can be made a friend of another class using keyword
friend.
Syntax
class A
{
friend class B; // class B is a friend class
......
}
class B
{
......
}
When a class is made a friend class, all the member functions of that class becomes friend
function.
If B is declared friend class of A then, all member functions of class B can access private and
protected data of class A but, member functions of class A can not private and protected data
of class B.
In below example you can access private function of class employee by using friend function.
Example
#include<iostream.h>
#include<conio.h>
class employee
{
private:
friend void sal();
};
void sal()
{
int salary=4000;
cout<<"Salary: "<<salary;
}
void main()
{
employee e;
sal();
getch();
}
Output
Salary: 4000
Q-2) What is class? Explain with example how objects are passed as argument
to member function and objects are returned from member function. (April
2017)
Class is a basic language construct of C++ for creating the user defined data type. They are
syntactically an extension of structures.
Objects can be passed as an argument to member function in three different ways
1. pass -by-value
2. pass-by-reference
3. pass-by-pointer
#include <iostream>
using namespace std;
class Complex
{
private:
int real;
int imag;
public:
Complex(): real(0), imag(0) { }
void readData()
{
cout << "Enter real and imaginary number respectively:"<<endl;
cin >> real >> imag;
}
void addComplexNumbers(Complex comp1, Complex comp2)
{
// real represents the real data of object c3 because this
function is called using code c3.add(c1,c2);
real=comp1.real+comp2.real;
void displaySum()
{
cout << "Sum = " << real<< "+" << imag << "i";
}
};
int main()
{
Complex c1,c2,c3;
c1.readData();
c2.readData();
c3.addComplexNumbers(c1, c2);
c3.displaySum();
return 0;
}
Output
In C++ programming, object can be returned from a function in a similar way as structures.
In this program, the sum of complex numbers (object) is returned to the main() function and
displayed.
#include <iostream>
using namespace std;
class Complex
{
private:
int real;
int imag;
public:
Complex(): real(0), imag(0) { }
void readData()
{
cout << "Enter real and imaginary number respectively:"<<endl;
cin >> real >> imag;
}
Complex addComplexNumbers(Complex comp2)
{
Complex temp;
void displayData()
{
cout << "Sum = " << real << "+" << imag << "i";
}
};
int main()
{
Complex c1, c2, c3;
c1.readData();
c2.readData();
c3 = c1.addComplexNumbers(c2);
c3.displayData();
return 0;
}
Inline Function is powerful concept in C++ programming language. 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.
To make any function inline function just preceded that function with inline keyword.
Whenever we call any function many time then, it take a lot of extra time in execution of series
of instructions such as saving the register, pushing arguments, returning to calling function. For
solve this problem in C++ introduce inline function.
Syntax
inline function_name()
//function body
Example
#include<iostream.h>
#include<conio.h>
void main()
{
show(); // Call it like a normal function
getch();
}
Output
Hello word
An array is a collection of similar data type value in a single variable. It is a derived data type
in C++, which is constructed from fundamental data type of C++ language.
Advantage of array
Code Optimization: Less code is required, one variable can store numbers of value.
Easy to traverse data: By using array easily retrieve the data of array.
Easy to sort data: Easily short the data using swapping technique
Random Access: With the help of array index you can randomly access any elements
from array.
Dis-Advantage of array
Fixed Size: Whatever size, we define at the time of declaration of array, we can not change
their size, if you need more memory in that time you can not increase memory size, and if you
need less memory in that case also wastage of memory.
Declaring Array
To declare an array in C++ required type of array elements and size of array.
Syntax
Datatype arrayName[SIZE];
Initializing Array
Initializing is a process to initialize the value in array variable. This is happen in two ways,
initialize array one by one or all elements are initializing once.
int arr[5];
arr[0]=10;
arr[1]=20;
arr[2]=30;
arr[3]=40;
arr[4]=50;
int arr[]={10,20,30,40,50};
We can access array elements with the help of index value of element.
#include<iostream.h>
#include<conio.h>
void main()
{
int i, marks[]={80, 62, 70, 90, 98}; //declaration and initialization of array
clrscr();
//traversal of array
for(i=0;i<5;i++)
{
cout<<endl<<marks[i];
}
getch();
Output
80
62
70
90
98
2-dimentional array
When we are working with 2-dimentional array we require to refer 2-subscript operator
which indicates row and column sizes.
On 2-dimentional array when we are referring one-subscript operator then if gives row
address, 2-subscript operator will gives element.
On 2-dimentional array arrayName always gives main memory that is 1st row base
address, arrayName will gives next row base address.
Syntax
Datatype ArrayName[SIZE][SIZE];
Always size of the array must be an unsigned integer value which is greater than '0' only. In
declaration of the array size must be required to mention, if size is not mention then compiler
will give an error.
Video Lectures @ https://www.youtube.com/c/TirupParmar Page 100
Prof. Tirup Parmar
Example
In declaration of the array size must be assigned type which value is greater than 0. In
initialization of the array if specific number of values are not initialized it then rest of all
elements will be initialized with it '0'.
Example
In initialization of the array mentioning the size is optional, in this case how many elements are
initialize it that many variable are created.
In implementation when we required 'n' number of variables of same data type then go for
an array.
When we are working with arrays always memory will created in continues memory
location, so randomly we can access the data.
In arrays all elements will share same name with unique identification value called index.
Always array index will start with '0' and end with 'size-1'.
When we are working with array compile time memory management will occur that is
static memory allocation.
Q-4) Write a C++ program to design a class - course For reading and
displaying the course information, the getInfo() and displayInfo() methods
will be used respectively. The getInfo() will be private method. Write down
C++ program to implement the class. (April 2017)
The process of creating and deleting objects in C++ is a vital task. Each time an instance of a
class is created the constructor method is called. Constructors is a special member function of
class and it is used to initialize the objects of its class. It is treated as a special member function
because its name is the same as the class name. These constructors get invoked whenever an
object of its associated class is created. It is named as “constructor” because it constructs the
value of data member of a class. Initial values can be passed as arguments to the constructor
function when the object is declared.
This can be done in two ways:
class class_name
{
int g, h;
public:
class_name(void); // Constructor Declared
. . .
};
class_name :: class_name()
{
g=1; h=2; // Constructor defined
}
Types of Constructors
C++ offers four types of constructors. These are:
1. Do nothing constructor
2. Default constructor
3. Parameterized constructor
4. Copy constructor
Do nothing Constructor
Do nothing constructors are that type of constructor which does not contain any statements. Do
nothing constructor is the one which has no argument in it and no return type.
Default Constructor
The default constructor is the constructor which doesn’t take any argument. It has no parameter
but a programmer can write some initialization statement there.
Syntax:
class_name()
// Constructor Definition ;
//Code Snippet:
#include <iostream>
class Calc
int val;
public:
Calc()
val = 20;
};
int main()
{ Calc c1;
A default constructor is very important for initializing object members, that even if we do not
define a constructor explicitly, the compiler automatically provides a default constructor
implicitly.
Parameterized Constructor
A default constructor does not have any parameter, but programmers can add and use parameters
within a constructor if required. This helps programmers to assign initial values to an object at
the time of creation.
Example:
#include <iostream>
class Calc
int val2;
public:
Calc(int x)
val2=x;
};
int main()
Calc c1(10);
Calc c2(20);
Calc c3(30);
Copy Constructor
C++ provides a special type of constructor which takes an object as an argument and is used to
copy values of data members of one object into another object. In this case, copy constructors are
used to declaring and initializing an object from another object.
Example:
Calc C2(C1);
Or
Calc C2 = C1;
The process of initializing through a copy constructor is called the copy initialization.
Syntax:
. . .
Example:
#include <iostream>
class CopyCon
int a, b;
public:
CopyCon(int x, int y)
a = x;
b = y;
void Display()
};
void main()
//Copy Constructor
Object.Display();
Object2.Display();
Destructor
Destructor is a member function which deletes an object. A destructor function is called
automatically when the object goes out of scope:
Features of destructor
~classname()
{
......
}
Note: If you do not specify a destructor, the compiler generates a default destructor for you.
#include<iostream.h>
#include<conio.h>
class sum
{
int a,b,c;
sum()
{
a=10;
b=20;
c=a+b;
cout<<"Sum: "<<c;
}
~sum()
{
cout<<<<endl;"call destructor";
}
delay(500);
};
void main()
{
sum s;
cout<<<<endl;"call main";
getch();
}
Output
Sum: 30
call main
call destructor
Explanation: In above example when you create object of class sum auto constructor of class
is call and after that control goes inside main and finally before end of program destructor is
call.