You are on page 1of 109

Prof.

Tirup Parmar

Prof. Tirup Parmar


F.Y. B.Sc(IT) Sem 2 OOPs notes with 2017 paper analysis

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

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 2


Prof. Tirup Parmar

UNIT I
Object Oriented Methodology

Introduction
A Brief Programming History

Computer Programming

An algorithm is a step-by-step process.


A computer program is a step-by-step set of
instructions for a computer.

Every computer program is an algorithm.

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

• Programming languages allow programmers to develop software.


• The three major families of languages are:
– Machine languages
– Assembly languages
– High-Level 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 languages are a step towards easier programming.


• Assembly languages are comprised of a set of elemental commands which are tied to a
specific processor.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 3


Prof. Tirup Parmar

• Assembly language code needs to be translated to machine language before the computer
processes it.
• Example:

ADD 1001010, 1011010

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

– Object-Oriented languages (OOP)

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

• The focus of OOP languages is not on structure, but on modeling data.


• Programmers code using “blueprints” of data models called classes.
• Examples of OOP languages include C++, Visual Basic.NET and Java.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 4


Prof. Tirup Parmar

Early programming languages

Modern programming languages

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 5


Prof. Tirup Parmar

Advantages and Disadvantages of Procedure Oriented Languages

Q) Write down advantages and disadvantages of procedure oriented language.


(April 2017)
Advantages of POP:-

 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.

Procedural oriented programming (pop):-


Traditional procedural-oriented languages
(such as C and Pascal) suffer some notable
drawbacks in creating reusable software
components:

1. The programs are made up of


functions. Functions are often
not reusable. It is very difficult to copy a
function from one program and reuse in
another program because the the function
is likely to reference the headers, global
variables and other functions. In other
words, functions are not well-
encapsulated as a self-contained reusable
unit.
2. The procedural languages are not
suitable of high-level abstraction for
solving real life problems. For example, C

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 6


Prof. Tirup Parmar

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.)

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 7


Prof. Tirup Parmar

E.g.:- c, basic, FORTRAN.

Characteristics of Procedural oriented programming:-

 It focuses on process rather than data.


 It takes a problem as a sequence of things to be done such as reading, calculating and
printing. Hence, a number of functions are written to solve a problem.
 A program is divided into a number of functions and each function has clearly defined
purpose.
 Most of the functions share global data.
 Data moves openly around the system from function to function.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 8


Prof. Tirup Parmar

Drawback of Procedural oriented programming (structured programming):-

 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.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 9


Prof. Tirup Parmar

Q-2) Explain Object Oriented Development. (2017)


Object-Oriented Programming (OOP) is the term used to describe a programming
approach based on objects and classes. The object-oriented paradigm allows us to organise
software as a collection of objects that consist of both data and behaviour. This is in contrast
to conventional functional programming practice that only loosely connects data and
behaviour.

The organization of data and functions is object oriented program is shown in fig.

Fig. organization of data and functions in oop


The data of an object can be accessed only by the functions associated with that object. However
functions of one object can access the functions of other objects.

Some of the features of object-oriented programming are: -


• Emphasis on data rather than procedure.
• Programs are divided into what are known as objects.
• Functions that operate on the data of an object are tide together in the
data structure.
• Data is hidden and cannot be accessed by external functions.
• Objects may communicate with each other through functions.
• New data and functions can be easily added whenever necessary.
• Follows bottom-up approach in program design.
• OOP facilitates creating reusable code that can eventually save a lot of
work.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 10


Prof. Tirup Parmar

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.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 11


Prof. Tirup Parmar

Q) CHARACTERISTICS OF OBJECT ORIENTED LANGUAGE


It is necessary to understand some of the concepts used extensively in objectoriented
programming. These include:

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:

 We do not have to open the case to use it.


 We have some controls to use it (buttons on the box, or a remote control).
 We can still understand the concept of a television, even if it is connected to a DVD player.
 It is complete when we purchase it, with any external requirements well documented.
 The TV will not crash!

In many ways this compares very well to the notion of a class.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 12


Prof. Tirup Parmar

Figure 1.1. The concept of a class - television example.

A class should:

 Provide a well-defined interface - such as the remote control of the television.


 Represent a clear concept - such as the concept of a television.
 Be complete and well-documented - the television should have a plug and should have a
manual that documents all features.
 The code should be robust - it should not crash, like the television.

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.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 13


Prof. Tirup Parmar

Figure 1.2. The Television class example.

An instance of a class is called an object.

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.

Figure 1.3. The Television objects example.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 14


Prof. Tirup Parmar

Encapsulation

The object-oriented paradigm encourages encapsulation. Encapsulation is used to hide the


mechanics of the object, allowing the actual implementation of the object to be hidden, so that we
don't need to understand how the object works. All we need to understand is the interface that is
provided for us.

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.

Figure 1.4. The Television interface example.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 15


Prof. Tirup Parmar

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.

For the user (who could be another programmer):

 The user need only understand the interface.


 The user need not understand how the implementation works or was created.

For 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:

 public methods - describe the interface.


 private methods - describe the implementation.

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.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 16


Prof. Tirup Parmar

Figure 1.5. The Television class example showing encapsulation.

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.

Figure 1.6. The Duck class showing inheritance.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 17


Prof. Tirup Parmar

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.

Figure 1.7. The grouped set of classes.

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.

Figure 1.8. The Base class and Derived class.

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.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 18


Prof. Tirup Parmar

Figure 1.9. The IS-A/IS-A-PART-OF relationships and the Vehicle class.

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.

So, using inheritance the programmer can:

 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

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 19


Prof. Tirup Parmar

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.

Figure 1.10. The over-ridden draw() method.

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.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 20


Prof. Tirup Parmar

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:

add (int x, int y)


add (String x, String y)

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.

What is the use?

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:

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 21


Prof. Tirup Parmar
virtual void raiseSalary()
{ /* common raise salary code */ }

virtual void promote()


{ /* common promote code */ }
};

class Manager: public Employee {


virtual void raiseSalary()
{ /* Manager specific raise salary code, may contain
increment of manager specific incentives*/ }

virtual void promote()


{ /* Manager specific promote */ }
};

// Similarly, there may be other types of employees

// We need a very simple function to increment salary of all employees


// Note that emp[] is an array of pointers and actual pointed objects can
// be any type of employees. This function should ideally be in a class
// like Organization, we have made it global to keep things simple
void globalRaiseSalary(Employee *emp[], int n)
{
for (int i = 0; i < n; i++)
emp[i]->raiseSalary(); // Polymorphic Call: Calls raiseSalary()
// according to the actual object, not
// according to the type of
pointer
}

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.

Q-4) Write down the benefits of using OOPs. (2017)

ADVANTAGES OF OBJECT ORIENTED PROGRAMING (OOP)


The object-oriented analysis has got many benefits when large projects are involved.
The benefits of using Object oriented analysis (OOA) are:
1. Tackle more challenging problem domains; OOA brings extra emphasis to the understanding
of problem domains.
2. OOA organizes analysis and specification using the methods of organization, which pervades
people’s thinking.
3. OOA uses inheritance, through which we can eliminate redundant code and extend the use of
existing classes.
4. It is easy to partition the work in a project based on objects.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 22


Prof. Tirup Parmar

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)

Data abstraction and encapsulation: -


Encapsulation: - encapsulation enables you to hide inside the object, both data fields and
functions that act on that data. The data is private to the object other parts of program cannot
have direct access to that data. Access to the data is possible through the objects interface.

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.

Q-6) What is inheritance? Explain with example the concept of multiple


inheritances. (2017)

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 23


Prof. Tirup Parmar

Q) Difference Between Procedure Oriented Programming (POP) & Object


Oriented Programming (OOP)
Object Oriented Programming
Procedure Oriented
Programming
Divided Into In POP, program is divided into In OOP, program is divided into parts
small parts called functions. called objects.
Importance In POP,Importance is not given In OOP, Importance is given to the
to data but to functions as well data rather than procedures or
as sequence of actions to be done. functions because it works as a real
world.
Approach POP follows Top Down approach. OOP follows Bottom Up approach.
Access Specifiers POP does not have any access OOP has access specifiers named
specifier. Public, Private, Protected, etc.
Data Moving In POP, Data can move freely from In OOP, objects can move and
function to function in the system. communicate with each other through
member functions.
Expansion To add new data and function in OOP provides an easy way to add new
POP is not so easy. data and function.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 24


Prof. Tirup Parmar

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

 Fundamental or primitive data types

 Derived data types

 User defined data types

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 25


Prof. Tirup Parmar

Primitive data types

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

Derived data types

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

int a[] = {10,20,30}; // valid


int b[] = {100, 'A', "ABC"}; // invalid

User defined data types

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];

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 26


Prof. Tirup Parmar

float sal;
};

In C++ language, user defined data types can be developed by using struct, union, enum etc.

Datatype Modifiers in C++

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.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 27


Prof. Tirup Parmar

Syntax

long a; --> by default which represent long int.

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

unsigned int a =100; // right


unsigned int a=-100; // wrong

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 28


Prof. Tirup Parmar

Signed

This keyword accepts both negative or positive value and this is default properties or data type
modifiers for every data type.

Example

int a=10; // right


int a=-10; // right
signed int a=10; // right
signed int a=-10;` // right

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;

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 29


Prof. Tirup Parmar

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;

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 30


Prof. Tirup Parmar

Variable assignment

It is a process of assigning a value to a variable.

Syntax
Variable_Name = value

Example

int a= 20;

int b;

Example

b = 25; // --> direct assigned variable

b = a; // --> assigned value in term of variable

b = a+15; // --> assigned value as term of expression

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 31


Prof. Tirup Parmar

Variable Declaration Rule in C++

To Declare any variable in C++ you need to follow rules and regulation of C++ Language,
which is given below;

 Every variable name should start with alphabets or underscore (_).

 No spaces are allowed in variable declaration.


 Except underscore (_) no special symbol are allowed in the middle of the variable
declaration.

 Maximum length of variable is 8 characters depend on compiler and operation system.

 Every variable name always should exist in the left hand side of assignment operator.

 No keyword should access variable name.


Note: In a c program variable name always can be used to identify the input or output data.

Variable declarations

This is the process of allocating sufficient memory space for the data in term of variable.

Syntax

Datatype variable_name;

int a;

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 32


Prof. Tirup Parmar

If no input values are assigned by the user than system will gives a default value called garbage
value.

Scope of Variable in C++

In C++ language, a variable can be either of global or local scope.

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.

Example of Global and Local variable


Example

#include<iostream.h>
#include<conio.h>

int a; // global variable


void main()
{
int b; // local variable
a=10, b=20;

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 33


Prof. Tirup Parmar

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

 Ternary or Conditional Operators

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 34


Prof. Tirup Parmar

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

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 35


Prof. Tirup Parmar

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<=10 True

> A>B True

>= A<=B False

== 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

&& (A<B) && (B>C) False

|| (B!=-C) || (A==B) True

! !(B<=-A) True

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 36


Prof. Tirup Parmar

Truth table of Logical Operator

C1 C2 C1 && C2 C1 || C2 !C1 !C2

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

=a=b Value of b will be assigned to a

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 37


Prof. Tirup Parmar

First C++ Program

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

This is my first program

 After writing complete code save the program using F2


 Save your code with .cpp extension for example: hello.cpp
 After save the code you need to compile your code using alt+f9
 Finally Run the program using clt+f9

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

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 38


Prof. Tirup Parmar

Compile and Run C++ Program

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

Compile -> alt+f9

Run -> clt+f9

Expression Evaluation in C++

In c language expression evaluation is mainly depends on priority and associativity.

Priority:

This represents the evaluation of expression starts from "what" operator.

Associativity:

It represents which operator should be evaluated first if an expression is containing more than
one operator with same priority.

Operator Priority Associativity

{}, (), [] 1 Left to right

++, --, ! 2 Right to left

*, /, % 3 Left to right

+, - 4 Left to right

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 39


Prof. Tirup Parmar

<, <=, >, >=, ==, != 5 Left to right

&& 6 Left to right

|| 7 Left to right

?: 8 Right to left

=, +=, -=, *=, /=, %= 9 Right to left

Example 1: Example 2:

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 40


Prof. Tirup Parmar

Types of Error in C++

Error is a abnormal condition whenever it occurs execution of the program is stopped these
are mainly classified into following types.

 Compile time error


 Run time error

Compile time error

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.

Example: Missing semicolon, writing keyword in upper case.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 41


Prof. Tirup Parmar

Run time error

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

Calling function without existence, divide by zero.

Int a=10,b;

B=a/0; --> infinite

Here out of range of int data type.

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.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 42


Prof. Tirup Parmar

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.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 43


Prof. Tirup Parmar

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 44


Prof. Tirup Parmar

Structure of C++ Program

Every C++ program can be written with the following syntax.

Syntax

#include<headerfilename.h> --> include section

class class_name
{
data members;
user defined method;
{
..........
..........
}
};

returntype main() --> main 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.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 45


Prof. Tirup Parmar

C++ library is collection of header files, header files is a container which is collection of related
predefined method.

User defined method section

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

methodName(); // calling method

Note: User defined method are Optional in a C++ program.

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.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 46


Prof. Tirup Parmar

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.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 47


Prof. Tirup Parmar

cout and cin in C++

cout<<: cout is used for print message on screen


Example

#include<iostream.h>
#include<conio.h>

void main()
{
int num;
clrscr();
cout<<"Hello word !"; // print message on screen
getch();
}

Output

Hello word !

cin

cin>>: cin is used for get or read value form keyboard.


Example

#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();
}

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 48


Prof. Tirup Parmar

Output

Enter any number :100

Number is: 100

main() Function in C++

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.

Simple example of main()

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 49


Prof. Tirup Parmar

Example

#include<stdio.h>
void main()
{
cout<<"This is main function";
}

Output

This is main function

Clrscr() and Getch() in C++

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();

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 50


Prof. Tirup Parmar

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

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 51


Prof. Tirup Parmar

Decision Making Statement

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

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 52


Prof. Tirup Parmar

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.

 For a single statement, it is not required to specify the body.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 53


Prof. Tirup Parmar

 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.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 54


Prof. Tirup Parmar

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";

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 55


Prof. Tirup Parmar

}
{
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.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 56


Prof. Tirup Parmar

Syntax

switch(expression/variable)

case value:

//statements

// any number of case statements

break; //optional

default: //optional

//statements

Rules for apply switch

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

Logical operators cannot be used with switch statement. For instance

Example

case k>=20: //is not allowed

Switch case variables can have only int and char data type. So float data type is not allowed.

Syntax

switch(ch)

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 57


Prof. Tirup Parmar

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.

Example of Switch case

#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:

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 58


Prof. Tirup Parmar

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

Enter any number (1 to 7): 5

Today is Friday

Note: In switch statement default is optional but when we use this in switch default is executed

at last whenever all cases are not satisfied the condition.

While Loop in C++

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.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 59


Prof. Tirup Parmar

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

Example of while Loop in C++

#include<iostream.h>
#include<conio.h>

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 60


Prof. Tirup Parmar

void main()
{
int i;
clrscr();
i=1;
while(i<5)
{
cout<<endl<<i;
i++;
}
getch();
}

Output

Output:

Execution process of while loop is slower than for loop.

For Loop in C++

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

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 61


Prof. Tirup Parmar

 Increment or Decrements
Syntax

for ( initialization; condition; increment )


{
statement(s);
}

 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

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 62


Prof. Tirup Parmar

Flow Diagram

Control flow of for loop

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 63


Prof. Tirup Parmar

 First initialize the variable

 In second step check condition

 In third step control goes inside loop body and execute.

 At last increase the value of variable

 Same process is repeat until condition not false.


Example of for loop

#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.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 64


Prof. Tirup Parmar

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);

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 65


Prof. Tirup Parmar

Flow Diagram

When use Do-While Loop

When you need to executes a block of code at least once, at that time do-while loop is use.

Example of do..while loop

#include<iostream.h>
#include<conio.h>

void main()
{
int i;
clrscr();
i=1;

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 66


Prof. Tirup Parmar

do
{
cout<<endl<<i;
i++;
}
while(i<5);
getch();
}

Output

1
2
3
4

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 67


Prof. Tirup Parmar

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.

A class in C++ contains, following properties;

 Data Member

 Method

 Constructor

 Block

 Class and Interface


Object: Object is a instance of class, object has state and behaviors.

An Object in C++ has three characteristics:

 State

 Behavior

 Identity
Syntax

class_name object_reference;

Example

Employee e;

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 68


Prof. Tirup Parmar

State: Represents data (value) of an object.

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.

Class is also can be used to achieve user defined data types.

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,

age as well as behaviors:- barking, eating, and sleeping.

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.

as we;; as behaviors - distance travel

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 69


Prof. Tirup Parmar

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 70


Prof. Tirup Parmar

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 71


Prof. Tirup Parmar

Difference between Class and Object in C++

Class Object

Class is a container which collection of


1 object is a instance of class
variables and methods.

Sufficient memory space will be


No memory is allocated at the time of
2 allocated for all the variables of class at
declaration
the time of declaration.

One class definition should exist only For one class multiple objects can be
3
once in the program. created.

Syntax to declare a Class


Syntax

class Class_Name

data member;

method;

Simple Example of Object and Class

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.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 72


Prof. Tirup Parmar

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

Enter salary: 4500

Salary: 4500

Access Specifiers in C++

Access specifiers in C++ define how the members of the class can be accessed. C++ has 3 new
keywords introduced, namely.

 public

 private

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 73


Prof. Tirup Parmar

 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.

Syntax of Declaring Access Specifiers in C++


Syntax

class

private:

// private members and function

public:

// public members and function

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 74


Prof. Tirup Parmar

protected:

// protected members and function

};

Public Access Specifier in C++

Public class members are accessible out side the class and it is available for every one.

Syntax

class Public_Access_Specifier

public: // public access specifier

int a; // Data Member Declaration

void display(); // Member Function declaration

Private Access Specifier in C++

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

private: // private access specifier

int a; // Data Member Declaration

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 75


Prof. Tirup Parmar

void display(); // Member Function declaration

Private and Public Access Specifier Example in C++


Example

#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;

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 76


Prof. Tirup Parmar

//'b' is public as can be accessed from any where


cout<<"value of b: "<<obj.b<<endl;
getch();
}

Note: If here, we access variable a in side main method it will give compile time error
Output

Accessing variable within the class


value of a: 10
value of b: 20
value of c: 30

Accessing variable outside the class


Value of b: 20

Protected Access Specifier in C++

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
}

Access Specifier Example in C++

In below example I will show you all these access specifier public, private and protected.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 77


Prof. Tirup Parmar

Access Specifier Example in C++

#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;
}
};

class Sub_class:public Declaration


{
public:
void show()
{
b=5;
c=6;
cout<<"\nAccessing variable in sub the class"<<endl;

// a is not accessible here it is private

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 78


Prof. Tirup Parmar

//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();

Sub_class s; // create object


s.show(); // Sub class show() function

cout<<"\nAccessing variable outside the class"<<endl;


//'a' cannot be accessed as it is private
//cout<<"value of a: "<<d.a<<endl;

//'b' is public as can be accessed from any where


cout<<"value of b: "<<d.b<<endl;

//'c' is protected and cannot be accesed here


//cout<<"value of c: "<<d.c<<endl;
getch();
}

Output

Accessing variable within the class

value of a: 10

value of b: 20

value of c: 30

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 79


Prof. Tirup Parmar

Accessing variable in sub class

value of b: 5

value of c: 6

Accessing variable outside the class

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().

Why use function ?

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

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 80


Prof. Tirup Parmar

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

 Develop an application in module format.

 Easily to debug the program.


 Code optimization: No need to write lot of code.

Type of Function

There are two type of function in C++ Language. They are;

 Library function or pre-define function.

 User defined function.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 81


Prof. Tirup Parmar

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.

Limitations of Library function

 All predefined function are contained limited task only that is for what purpose function is
designed for same purpose it should be used.

 As a programmer we do not having any controls on predefined function implementation


part is there in machine readable format.

 In implementation whenever a predefined function is not supporting user requirement then


go for user defined function.

User defined function

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;

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 82


Prof. Tirup Parmar

 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 ';'.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 83


Prof. Tirup Parmar

Example of Function in C++

#include<iostream.h>
#include<conio.h>

void sum(); // declaring a function


int a=10,b=20, c;

void sum() // defining function


{
c=a+b;
cout<<"Sum: "<<c;
}
void main()
{
clrsct();
sum(); // calling function
}

Output

Sum: 30

Function Arguments in C++

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

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 84


Prof. Tirup Parmar

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;

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 85


Prof. Tirup Parmar

getch();
}

Output

Value of a: 200

Value of b: 100

Call by reference

In call by reference, original value is changed or modified because we pass reference


(address). Here, address of the value is passed in the function, so actual and formal arguments
shares the same address space. Hence, any value changed inside the function, is reflected inside
as well as outside the function.
Example Call by Reference 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();

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 86


Prof. Tirup Parmar

Output

Value of a: 200

Value of b: 100

Difference Between Call by Value and Call by Reference.

call by Value call by Reference

This method copy original value into This method copy address of arguments into
function as a arguments. function as a arguments.

Changes made to the parameter affect the


Changes made to the parameter inside the
argument. Because address is used to access the
function have no effect on the argument.
actual argument.

Actual and formal arguments will be Actual and formal arguments will be created in
created in different memory location same memory location

Note: By default, C++ uses call by value to pass arguments.

C++ function call by pointer


The call by pointer method of passing arguments to a function copies the address of an argument
into the formal parameter. Inside the function, the address is used to access the actual argument
used in the call. This means that changes made to the parameter affect the passed argument.

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.

// function definition to swap the values.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 87


Prof. Tirup Parmar

void swap(int *x, int *y) {

int temp;

temp = *x; /* save the value at address x */

*x = *y; /* put y into x */

*y = temp; /* put x into y */

return;

For now, let us call the function swap() by passing values by pointer as in the following example

#include <iostream>

using namespace std;

// function declaration

void swap(int *x, int *y);

int main () {

// local variable declaration:

int a = 100;

int b = 200;

cout << "Before swap, value of a :" << a << endl;

cout << "Before swap, value of b :" << b << endl;

/* calling a function to swap the values.

* &a indicates pointer to a ie. address of variable a and

* &b indicates pointer to b ie. address of variable b.

*/

swap(&a, &b);

cout << "After swap, value of a :" << a << endl;

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 88


Prof. Tirup Parmar

cout << "After swap, value of b :" << b << endl;

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

After swap, value of a :200


After swap, value of b :100

Q-1) What is friend function? Write a friend function to display mark sheet of
the F. Y. B. Sc. IT student. (April 2017)

Friend Function in C++

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.

Why use friend function ?

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

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 89


Prof. Tirup Parmar

{
......
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.

Note: Remember, friendship relation in C++ is always granted not taken.

Example Friend function

In below example you can access private function of class employee by using friend function.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 90


Prof. Tirup Parmar

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

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 91


Prof. Tirup Parmar

In C++ programming, objects can be passed to a function in a similar way as structures.

How to pass objects to a function?

Example 1: Pass Objects to Function

C++ program to add two complex numbers by passing objects to a function.

#include <iostream>
using namespace std;

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 92


Prof. Tirup Parmar

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;

// imag represents the imag data of object c3 because this


function is called using code c3.add(c1,c2);
imag=comp1.imag+comp2.imag;
}

void displaySum()
{
cout << "Sum = " << real<< "+" << imag << "i";
}
};
int main()
{

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 93


Prof. Tirup Parmar

Complex c1,c2,c3;
c1.readData();
c2.readData();
c3.addComplexNumbers(c1, c2);
c3.displaySum();
return 0;
}

Output

Enter real and imaginary number respectively:


2
4
Enter real and imaginary number respectively:
-3
4
Sum = -1+8i

How to return an object from the function?

In C++ programming, object can be returned from a function in a similar way as structures.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 94


Prof. Tirup Parmar

Example 2: Pass and Return Object from the Function

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;

// real represents the real data of object c3 because this


function is called using code c3.add(c1,c2);
temp.real = real+comp2.real;

// imag represents the imag data of object c3 because this


function is called using code c3.add(c1,c2);
temp.imag = imag+comp2.imag;
return temp;
}

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 95


Prof. Tirup Parmar

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;
}

Q-3) What is inline function? Explain with example. (April 2017)

Inline Function in C++

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.

Why use Inline function

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.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 96


Prof. Tirup Parmar

Advantage of Inline Function

The main advantage of inline function is it make the program faster.

Syntax

inline function_name()

//function body

Example

#include<iostream.h>
#include<conio.h>

inline void show()


{
cout<<"Hello world";
}

void main()
{
show(); // Call it like a normal function
getch();
}

Output

Hello word

Where inline function not work ?


 If inline function are recursive
 If function contain static variables.
 If return statement are exits but not return any value.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 97


Prof. Tirup Parmar

Array in C++ Language

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];

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 98


Prof. Tirup Parmar

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.

Initialization of array one by one

int arr[5];
arr[0]=10;
arr[1]=20;
arr[2]=30;
arr[3]=40;
arr[4]=50;

Initialization of array at once

int arr[]={10,20,30,40,50};

Accessing Array Elements in C++

We can access array elements with the help of index value of element.

Example of Array in C++

#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();

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 99


Prof. Tirup Parmar

Output

80

62

70

90

98

2-dimentional array

 In 2-dimentional elements are arranged in row and column format.

 When we are working with 2-dimentional array we require to refer 2-subscript operator
which indicates row and column sizes.

 The main memory of 2-dimentional array is rows and sub-memory is columns.

 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];

Important points related to array

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

int arr[]; //error

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

int arr[5]={10,20}; // yes valid


arr[0]=10;
arr[1]=20;
arr[2], arr[3], arr[4]; // initialized with zero

In initialization of the array mentioning the size is optional, in this case how many elements are
initialize it that many variable are created.

Example of Array in C++

int arr[]={10,20,30,40,50}; // valid


Size=5;
Sizeof(arr)=10 byte

Important points for Array

 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'.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 101


Prof. Tirup Parmar

 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)

Solution: follow class notes

Q-5) What is use of constructor? Explain with example parameterized


constructor. (April 2017)

What are constructors?

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:

 By calling constructor explicitly


 By calling constructor implicitly

The declaration and definition of constructor is as follows


syntax:

class class_name
{
int g, h;
public:
class_name(void); // Constructor Declared
. . .
};

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 102


Prof. Tirup Parmar

class_name :: class_name()
{
g=1; h=2; // Constructor defined
}

Special characteristics of Constructors:


 They should be declared in the public section
 They do not have any return type, not even void
 They get automatically invoked when the objects are created
 They cannot be inherited though derived class can call the base class constructor
 Like other functions, they can have default arguments
 You cannot refer to their address
 Constructors cannot be virtual

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()

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 103


Prof. Tirup Parmar

// Constructor Definition ;

//Code Snippet:

#include <iostream>

using namespace std;

class Calc

int val;

public:

Calc()

val = 20;

};

int main()

{ Calc c1;

cout << c1.val;

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.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 104


Prof. Tirup Parmar

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>

using namespace std;

class Calc

int val2;

public:

Calc(int x)

val2=x;

};

int main()

Calc c1(10);

Calc c2(20);

Calc c3(30);

cout << c1.val2;

cout << c2.val2;

cout << c3.val2;

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 105


Prof. Tirup Parmar

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:

class-name (class-name &)

. . .

Example:

#include <iostream>

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 106


Prof. Tirup Parmar

using namespace std;

class CopyCon

int a, b;

public:

CopyCon(int x, int y)

a = x;

b = y;

cout << "\nHere is the initialization of Constructor";

void Display()

cout << "\nValues : \t" << a << "\t" << b;

};

void main()

CopyCon Object(30, 40);

//Copy Constructor

CopyCon Object2 = Object;

Object.Display();

Object2.Display();

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 107


Prof. Tirup Parmar

Destructor
Destructor is a member function which deletes an object. A destructor function is called
automatically when the object goes out of scope:

When destructor call


 when program ends
 when a block containing temporary variables ends
 when a delete operator is called

Features of destructor

 The same name as the class but is preceded by a tilde (~)

 no arguments and return no values


Syntax

~classname()
{
......
}

Note: If you do not specify a destructor, the compiler generates a default destructor for you.

Q-6) Write a C++ program to demonstrate the use of constructor and


destructor. (April 2017)
Example of Destructor in C++

#include<iostream.h>
#include<conio.h>
class sum
{
int a,b,c;
sum()
{
a=10;
b=20;
c=a+b;

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 108


Prof. Tirup Parmar

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.

Video Lectures @ https://www.youtube.com/c/TirupParmar Page 109