8535 Decap202 Object Oriented Programming
8535 Decap202 Object Oriented Programming
DECAP202
Edited by
Balraj Kumar
Object Oriented Programming
Edited By:
Balraj Kumar
CONTENT
Dr. Prikshat Kumar Angra, Lovely Professional University Unit 01:Principles of OOP
Objectives
After studying this unit, you will be able to:
● Recognize the basic concept of object-oriented programming
● Describe the OOP languages
● Understand Basics of C++
● Compare the procedural Oriented and object-oriented programming
Introduction
Over the last few decades, programming practices have changed dramatically. As more
programmers gained competence, previously undiscovered difficulties began to emerge. The
programming community became increasingly worried about the programming philosophy they
use and the methodologies they use in software development.
Productivity, reliability, cost effectiveness, reusability, and other factors began to become key
concerns. Many conscious attempts were made to comprehend these issues and find potential
answers. This is precisely why a growing number of programming languages have been developed
and are still being developed. Furthermore, techniques to programme creation have been the
subject of extensive research, resulting in the development of several frameworks. The object-
oriented programming method, or simply OOP, is one such approach, and it is perhaps the most
common.
C++ programming's main goal is to introduce the concept of object orientation to the C
programming language.
Inheritance, data binding, polymorphism, and other notions are all part of the Object Oriented
Programming paradigm.
1. Objects
2. Classes
3. Data abstraction
4. Data encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic binding
8. Message passing
Let us now study the entire concept in detail.
1. Objects: Objects are the basic run-time entities in an object-oriented system. They may
represent a person, a place, a bank account, a table of data; they may also represent user-
defined data such as vectors, time and lists.
They occupy space in memory that keeps its state and is operated on by the defined operations on
the object. Each object contains data and code to manipulate the data.
Notes: -Objects can interact without having to know details of each other data or code.
2. Classes: A class represents a set of related objects. The object has some attributes, whose
value consist much of the state of an object. The class of an object defines what attributes an
object has. The entire set of data and code of an object can be made a user-defined data type
with the help of a class.
Classes are user defined data types that behave like the built-in types of a programming language.
Classes have an interface that defines which part of an object of a class can be accessed from outside
and how. A class body that implements the operations in the interface, and the instance variables
that contain the state of an object of that class.
Notes:- A class is a data-type that has its own members i.e. data members and member
functions. It is the blueprint for an object in objects oriented programming language. It is the basic
building block of object oriented programming in c++.
The data and the operation of a class can be declared as one of the three types:
(a) Public: These are declarations that are accessible from outside the class to anyone who can
access an object of this class.
(b) Protected: These are declarations that are accessible from outside the class to anyone who
can access an object of this class.
(c) Private: These are declarations that are accessible only from within the class itself.
Syntax of class
class class_name {
data_typedata_name;
return_typemethod_name(parameters);
}
3. Data Abstraction: - Data abstraction or Data Hiding is the concept of hiding data and
showing only relevant data to the final user. It is also an important part object oriented
programing.
Let’s take real life example to understand concept better, when we ride a bike we only
know that pressing the brake will stop the bike and rotating the throttle will accelerate but
you don't know how it works and it is also not think we should know that's why this is
done from the same as a concept data abstraction.
In C plus plus programming language write two ways using which we can accomplish data
abstraction −
1. using class
2. using header file
Example: - We can represents essential features without including background details and
explanations.
index of text book.
class School
{
void sixthc lass();
void seventhclass();
void tenthclass();
}
Notes: - Inheritance allows us to create a new class (derived class) from an existing class (base
class).
Caution: - Keep in mind that each subclass defines only those features that are unique to it.
16 + 4 = 20
“xyz” + “sqr” = “xyzsqr”
Example: - A person can have more than one behavior depending upon the situation. like a
woman a mother, manager and a daughter And this define her behavior. This is from where the
concept of polymorphism came from.
In c++ programming language, polymorphism is achieved using two ways. They are operator
overloading and function overloading.
This is associated with polymorphism and inheritance. A function call associated with a
polymorphic reference depends on the dynamic type of that reference. For example in the above
figure, by inheritance, every object will have this procedure. Its algorithm is, however, unique to
each object so the procedure will be redefined in each class that defines the objects. At run-time, the
code matching the object under reference will be called.
Example
#include<iostream>
using namespace std;
class demo{
public:
int f_num,s_num;
sum(int a,int b){
cout<<a+b;
}
};
main(){
demo d1;
d1.sum(d1.f_num=10,d1.s_num=39);
return 0;
}
In the modern programming parlance, at least in most of the commercial and business applications
areas, programming has been made independent of the target machine. This machine independent
characteristic of programming has given rise to a number of different methodologies in which
programs can now be developed. We will particularly concern ourselves with two broad
programming approaches – or paradigm as they are called in the present context.
1. Procedure-oriented paradigm
2. Object-oriented paradigm
Many key data items are put as global in a multi-function software so that they can be accessible by
all functions. It's possible that each function has its own set of local data. Global data are more
vulnerable to a function's unintended alteration. It's difficult to figure out which data is used by
which function in a huge software. If we need to make changes to an external data structure, we
must likewise make changes to any functions that access the data. Bugs will be able to get in
through this opening.
Another serious drawback with the procedural approach is that we do not model real world
problems very well. This is because functions are action-oriented and do not really corresponding
to the element of the problem.
Secondly, OOP has nothing to do with any programming language, although a programming
language that supports OOP makes it easier to implement the object-oriented techniques. As
you will see shortly, with some discipline, you can use objects even in C programs.
o Attributes: Attributes are data that define the traits of an object. This data can be
as simple as integers and real numbers. It can also be a reference to a complex
object.
o Methods: They define the behavior and are also called functions or procedures.
● Simulation and modelling: Another area where OOP approach criteria might be counted is
system modelling. Because OOP programmers are easier to grasp, it is preferable to
represent a system in a simpler form when using the OOP approach.
● AI and expert systems: These are computer applications that are developed to solve
complex problems pertaining to a specific domain, which is at a level far beyond the reach of
a human brain.
It has the following characteristics:
o Reliable
o Highly responsive
o Understandable
o High-performance
● Neural networks and parallel programming: It address the problem of prediction and
approximation of complex time-varying systems. Firstly, the entire time-varying process is
split into several time intervals or slots. Then, neural networks are developed in a particular
time interval to disperse the load of various networks. OOP simplifies the entire process by
simplifying the approximation and prediction ability of networks.
Example
#include<iostream>
using namespace std;
class find_sum{
public:
int x,y;
int sum();
};
int find_sum ::sum(){
return x+y;
}
Example
#include <iostream>
using namespace std;
class Box {
public:
double length;
void setWidth( double wid );
double getWidth( void );
private:
double width;
};
double Box::getWidth(void) {
return width ;
}
Summary
● Programming practices have evolved considerably over the past few decades.
● By the end of last decade, millions and millions of lines of codes have been designed and
implemented all over the word.
● The main objective is to reuse these lines of codes. More and more software development
projects were software crisis.
● It is this immediate crisis that necessitated the development of object-oriented approach
which supports reusability of the existing code.
● Software is not manufactured. It is evolved or developed after passing through various
developmental phases including study, analysis, design, implementation, and
maintenance.
● Conventional programming using high level languages such as COBOL, FORTRAN and C
is commonly known as procedures-oriented programming.
● In order to solve a problem, a hierarchical decomposition has been used to specify the
tasks to be completed.
● OOP is a method of designing and implementing software.
● Since OOP enables you to remain close to the conceptual, higher-level model of the real
world problem, you can manage the complexity better than with approaches that force
you to map the problem to fit the features of the language.
● Some essential concepts that make a programming approach object-oriented are objects,
classes, Data abstraction, Data encapsulation, Inheritance, Polymorphism, dynamic
binding and message passing.
● The data and the operation of a class can be disclosed public, protected or private. OOP
provides greater programmer productivity, better quality of software and lesser
maintenance cost.
Keywords
Classes: A class represents a set of related objects.
Data Abstraction: Abstraction refers to the act of representing essential-features without
including the background details or explanations.
Data Encapsulation: The wrapping up to data and functions into a single unit (class) is known as
encapsulation.
Design: The term design describes both a final software system and a process by which it is
developed.
Dynamic Binding: Binding refers to the linking of a procedure call to the code to be executed in
response to the call.
Inheritance: Inheritance is the process by which objects of one class acquire the properties of
objects of another class.
Message Passing: Message passing is another feature of object-oriented programming.
Object-oriented Programming Paradigm: The term object-oriented programming (OOP) is
widely used, but experts do not seem to agree on its exact definition.
Objects: Objects are the basic run-time entities in an object-oriented system.
Polymorphism: Polymorphism means the ability to take more than one form.
Self Assessment
1. Which feature of OOPS described the reusability of code?
A. Abstraction
B. Encapsulation
C. Polymorphism
D. Inheritance
7. Which of the following OOP concept is not true for the C++ programming language?
A. A class must have member functions
B. C++ Program can be easily written without the use of classes
C. At least one instance should be declared within the C++ program
D. C++ Program must contain at least one class
8. What is the extra feature in classes which was not in the structures?
A. Member functions
B. Data members
C. Public access specifier
D. Static Data allowed
12. Which among the following feature does not come under the concept of OOPS?
A. Platform independent
B. Data binding
C. Data hiding
D. Message passing
13. The combination of abstraction of the data and code is viewed in________.
A. Inheritance
B. Class
C. Object
D. Interfaces
15. Which syntax among the following shows that a member is private in a class?
A. private::Name(parameters)
B. private: function Name(parameters)
C. private(function Name(parameters))
D. private function Name(parameters)
6. B 7. D 8. A 9. D 10. B
Review Questions
1. Discuss basic concepts of C++ in detail.
2. Inheritance is the process by which objects of one class acquire the properties of objects of
another class. Analyze.
3. Examine what are the benefits of OOP?
4. Compare what you look for in the problem description when applying object-oriented
approach in contrast to the procedural approach. Illustrate with some practical examples.
5. What is OOP? Explain the applications of object oriented programming in detail.
6. Differentiate procedural programming and object oriented programming.
7. Write programs that demonstrate working of classes and objects
Further Readings
E. Balagurusamy, Object-oriented Programming through C++, Tata McGraw Hill.
Herbert Schildt, The Complete Reference – C++, Tata Mc Graw Hill.
Robert Lafore, Object-oriented Programming in Turbo C++, Galgotia Publications
Web Links
https://en.wikipedia.org/wiki/Object-oriented_programming
www.web-source.net
www.webopedia.com
Objectives
After studying this unit, you will be able to:
Recognize the tokens
Understand keywords
Describe the expressions
Recognize the reference variable
Introduction
C++ is a language in essence. It is made up of letters, words, sentences, and constructs just like
English language. This unit discusses these elements of the C++ language along with the operators
applicable over them.
2.1 What is C?
It is a very powerful and general-purpose language used in programming. We can use C to develop
software such as databases, operating systems, compilers, and many more. This programming
language is excellent to learn for beginners in programming.
Parameter C C++
Support for OOPs Feature C has no support for the The C++ language supports
OOPs concept. Thus, it does encapsulation, inheritance, and
not support encapsulation, polymorphism because it is an
polymorphism, and object-oriented programming
inheritance. language.
Segregation of Data and Since C is a procedural In the case of C++, the data
Functions programming language, the and functions stay
data and functions stay encapsulated in an object’s
separate in it. form.
Hiding Data and Information C does not support the hiding C++ language hides the data
of data and information. through encapsulation. This
process ensures that a user
utilizes the structures as
operators as intended.
Built-in Data Types The C language does not The C++ language supports
support built-in data types. built-in data types.
Function Inside Structures In the case of C, it does not In the case of C++, it uses
define the functions inside functions inside a structure.
structures.
Namespace Features The namespace feature The C++ language uses the
groups various entities like namespace features to help
objects, classes, and functions avoid name collisions.
under a specific name. No
namespace features are
present in the C language.
Virtual and Friend Functions The C language does not The C++ language supports
support virtual and friend virtual and friend functions.
functions.
Allocation and Deallocation The C language provides The C++ language provides a
of Memory calloc() and malloc() for new operator for the allocation
dynamic allocation of of memory and a delete
memory and free() for operator for the deallocation of
deallocation of memory. memory.
Exception Handling It does not provide any direct It provides direct support for
support for exceptional exceptional handling. The C++
handling. C language requires language uses a try-catch
the usage of functions that block.
support exception handling.
Function for Input/Output The C language uses the In the C++ language, it uses
scanf() and printf() functions the cin and cout for the input
for the input and output and output operations.
operations.
Example
// Simple C++ Program
#include <iostream>
using namespace std;
int main() {
cout << "Hello world!";
return 0;
}
Output
Note
; is used to indicate the end of a statement.
The object code is combined with the required supporting code to make an executable program.
2.8 Keywords
The keywords implement specific C++ language features. They are explicitly reserved identifiers
and cannot be used as names for the program variables or other user-defined program elements.
2.9 Identifiers
Identifiers refer to the names of variables, functions, arrays, classes, etc., created by the
programmer. They are the fundamental requirement of any language. Each language has its own
rules for naming these identifiers. The following rules are common to both C and C++:
1. Only alphabetic characters, digits, and underscores are permitted.
2. The name cannot start with a digit.
3. Uppercase and lowercase letters are distinct.
4. A declared keyword cannot be used as a variable name.
A major difference between C and C++ is the limit on the length of a name. While ANSI
Crecognizes only the first 32 characters in a name, C++ places no limit on its length and,
therefore,all the characters in a name are significant.
Care should be exercised while naming a variable that is being shared by more than one
filecontaining C and C++ programs. Some operating systems impose a restriction on the length
ofsuch a variable name.
Caution
The first character in an identifier must be a letter or the _ (underscore) character; however,
beginning identifiers with an underscore is considered a poor programming style.
2.10 Constants
In C++, we can create variables whose value cannot be changed. const keyword is used for declare
constant.
Example
const float pi = 3.14;
Types of Constants in C++
1. Integer constants
2. Floating cconstants
3. Character constants
4. String constants
5. Octal constants
2.11 Strings
A string stores a sequence of characters.
It terminates with a null character ‘\0’.
Unlike characters, strings in C++ are always enclosed within double quotes (” “).
Example
char name[30] = ‘’Hello”;
2.12 Operators
Operators are symbols that operate on operands. These operands can be variables or values.
Operators help us to perform mathematical and logical computations.
Common C++ Operators are
1. Arithmetic
2. Assignment
3. Relational
4. Logical
5. Bitwise
6. Other operators
Lab Excercise
#include<iostream>
using namespace std;
int main(){
int x=30;
int &r=x;
cout<<r;
return 0;
}
Output
Summary
C++ language is made up of letters, words, sentences and constructs just like English
language.
A collection of characters, much like a word in English language are called tokens.
A token can be a keyword, or identifier, constant, string or an operator.
Keywords are the reserve words that cannot be used as names of variable or other
userdefined program elements.
Identifiers refer to the names of variables, functions, arrays, classes etc. created by the
programmer, Basic types.
An array represents named list of finite number of similar data elements. A function is a
named part of a program that can be invoked from the other parts of the program.
A pointer is a variable that holds a memory address of another variable. A reference is an
alternative name for an object. A constant is a data item whose data value can never
change during the program run.
Keywords
Character Constant: One or more characters enclosed in single quotes.
Expression: A combination of variables, constants and operators written according to some
rules.
SelfAssessment
1. What is C++?
A. C++ is an object oriented programming language
B. C++ is a procedural programming language
C. C++ supports both procedural and object oriented programming language
D. C++ is a functional programming language
int main()
printf("1024");
return 0;
A. 1024
B. 10
C. Error
D. 0
int main() {
double a;
return 0;
A. 1
B. 0
C. 8
D. 4
6. C 7. B 8. B 9. B 10. D
Review Questions
1. Explain various types of data types in c++.
2. What is a constant?
3. Why keywords required in the programming? Explain.
4. Write a program that performs reference operation.
5. Explain different types of operators.
Further Readings
E Balagurusamy; Object-oriented Programming with C++; Tata Mc Graw-
Hill.
Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill.
Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.
Web Links
http://msdn.microsoft.com/en-us/library/wcz57btd(v=vs.80).aspx
https://www.codecademy.com/learn/learn-c-plus-plus
Dr. Prikshat Kumar Angra, Lovely Professional University Unit 03: Operators and Type Casting
Objectives
After studying this unit, you will be able to:
Introduction
It is the transformation of one type into another. Type casting, in other terms, is the process of
transforming an expression of one type into another.Conversion of variables from one type to
another are known as type conversion. Type conversions ultimate aim is to make variables of one
data type work with variables of another data type.Type conversions can be used to force the
correct type of mathematical computation needed to be performed.
Depending on whether the type conversion is ordered by the programmer or the compiler, it can be
explicit or implicit. When a programmer wants to go around the compiler's typing system, he or
she uses explicit type conversions (casts); however, the programmer must use them appropriately
to succeed. Problems that the compiler avoids may develop, such as when the processor requires
data of a certain type to be stored at specific addresses or when data is truncated because a data
type on a given platform does not have the same size as the original type. Explicit type conversions
between objects of different kinds result in difficult-to-read code at best.
Example
int c = a + b;
Here, ‘+’ is the addition operator. ‘a’ and ‘b’ are the operands that are being ‘added’.
1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators
5. Bitwise Operators
6. Other Operators
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on variables and data. For example,
E Example
a+b;
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
Assignment Operators
Assignment operators are used to assign values to variables. For example,
Example
X=10;
Here, we have assigned x value of 5 to the variable x..
Operator Example
= x = y;
+= x += y;
-= x -= y;
*= x *= y;
/= x /= y;
%= x %= y;
Relational Operators
A relational operator is used to check the relationship between two operands. For example,
Example
a > b;
Here, > is a relational operator. It checks if a is greater than b or not.
If the relation is true, it returns 1 whereas if the relation is false, it returns 0.
Logical Operators
Logical operators are used to check whether an expression is true or false. If the expression is true,
it returns 1 whereas if the expression is false, it returns 0.
Logical AND.
&& expression1 && expression2 True only if all the operands
are true.
Logical OR.
|| expression1 || expression2 True if at least one of the
operands is true.
Logical NOT.
! !expression True only if the operand is
false.
Bitwise Operators
In C++, bitwise operators are used to perform operations on individual bits. They can only be used
alongside char and int data types.
Operator Description
| Binary OR
^ Binary XOR
Example
#include<iostream>
using namespace std;
int main()
{
int n= 50;
int *ptr;
ptr=&n;
cout<<"\nAddress of n ="<<&n;
cout<<"\nValue in variable ptr ="<< ptr;
cout<<"\nValue of n ="<<n;
cout<<"\nValue using dereferencing operator="<<*ptr;
return 0;
}
Output
Example
int a = 45;
float b= 1253.25;
a=b;
This converts float variable b to an integer before its value assigned to a. The type conversion is
automatic as far as data types involved are built in types. We can also use the assignment operator
in case of objects to copy values of all data members of right hand object to the object on left hand.
The objects in this case are of same data type.
Lab Excersise
//Program
#include <iostream>
using namespace std;
int main()
{
int x = 100;
char y = 'a';
x = x + y;
float z = x + 1.0;
cout << "x = " << x << endl
<< "y = " << y << endl
<< "z = " << z << endl;
return 0;
}
Output
Lab Exercise
//Program
#include <iostream>
using namespace std;
int main()
{
double x = 25.5;
int sum = (int)x + 1;
cout << "Sum = " << sum;
return 0;
There are three types of situations that arise where data conversion are between incompatible
types. Possible Type Conversions in C++
Example
string s1, s2;
char* name1 = “Good Morning”;
char* name2 = “STUDENTS” ;
s1 = string(name1);
s2 = name2;
The program statement
s1 = string (name1);
first converts name1 from char* type to string type and then assigns the string type values to the
object s1. The statement
s2 = name2;
performs the same job by invoking the constructor implicitly.
Consider the following example
class time
{
int hours;
int minutes;
Lab exercise
// Program - Using Constructor
#include<iostream>
using namespace std;
class Time
{
int hrs,min;
public:
Time(int t)
{
cout<<"Basic Type to Class Type Conversion...\n";
hrs=t/60;
min=t%60;
}
void show();
};
void Time::show()
{
cout<<hrs<< ": Hours(s)" <<endl;
cout<<min<< " Minutes" <<endl;
}
int main()
{
int duration;
cout<<"\nEnter time duration in minutes";
Output
Lab exercise
// Program - Using Operator
#include<iostream>
using namespace std;
class Time
{
int hrs,min;
public:
void display()
{
cout<<hrs<< ": Hour(s)\n";
cout<<min<<": Minutes\n";
}
void operator =(int t)
{
cout<<"\nBasic Type to Class Type Conversion...\n";
hrs=t/60;
min=t%60;
}
};
int main()
{
Time t1;
int duration;
cout<<"Enter time duration in minutes";
Output
Notes
• In this conversion source type is basic type and the destination type is class type.
• Basic data type is converted into class type.
Lab exercise
// Program
#include<iostream>
using namespace std;
class Time
{
int h,m;
public:
Time(int a,int b)
{
h=a;
m=b;
}
operator int()
{
cout<<"\nClass Type to Basic Type Conversion...";
return(h*60+m);
}
~Time()
{
cout<<"\nDestructor called..."<<endl;
}
Output
Notes
Class type to basic type conversion requires special casting operator function for class type to basic
type conversion. This is known as the conversion function.
Example
The following Table summarizes all the three conversions. It shows that the conversion from a class
to any other type (or any other class) makes use of a casting operator in the source class. To
performthe conversion from any other type or class to a class type, a constructor is used in the
destination class.
When a conversion using a constructor is performed in the destination class, we must be able to
access the data members of the object sent (by the source class) as an argument.
Lab Exercise
// Program – Using Constructor
#include<iostream>
using namespace std;
int getMinutes()
{
int tot_min = ( hrs * 60 ) + min ;
return tot_min;
}
void display()
{
cout<<"Hours: "<<hrs<<"\n";
cout<<" Minutes : "<<min <<"\n";
}
};
class Minute
{
int min;
public:
Minute()
{
min = 0;
}
void operator=(Time T)
{
min=T.getMinutes();
}
void display()
{
cout<<"\n Total Minutes : " <<min<<"\n";
Lab Exercise
//Program – Using conversion function
#include<iostream>
using namespace std;
class inventory1
{
int ino,qty;
float rate;
public:
inventory1(int n,intq,float r)
{
ino=n;
qty=q;
rate=r;
}
int getino()
Which form to use, depends upon where we want the type-conversion function to be
located, whether in the source class or in the destination class.
Keywords
Implicit Conversion: An implicit conversion sequence is the sequence of conversions required to
convert an argument in a function call to the type of the corresponding parameter in a function
declaration.
Explicit Conversion:
Operator Typename(): Converts the class object of which it is a member to typename.
Self Assessment
1. Following program is an example of ___________ conversion.
#include <iostream>
int main()
int x = 100;
char y = 'a';
x = x + y;
float z = x + 1.0;
return 0;
A. Implicit
B. Explicit
C. Both
D. None of Above
6. What will be the data type of the result of the following operation?
(float)a * (int)b / (long)c * (double)d
A. int
B. long
C. float
D. double
9. Which of the following is correct statement for class to basic type conversion?
11. Conversion function must not specify the return value even though it returns the value.
A. True
B. False
12. To convert from a user defined class to a basic type, you would most likely use.
A. Built-in conversion function
B. A one-argument constructor
C. A conversion function that’s a member of the class
D. An overloaded ‘=‘operator
13. How many ways to perform conversion from one class to another class can perform?
A. 4
B. 2
C. 3
D. 1
14. ____ refers to the process of changing the data type of the value stored in a variable.
A. Type char
B. Type int
C. Type float
D. Type cast
15. Which of the following type-casting have chances for wrap around?
A. From int to float
B. From int to char
C. From char to short
D. From char to int
6. D 7. C 8. D 9. B 10. C
Further Readings
E Balagurusamy; Object-oriented Programming with C++; Tata Mc Graw-Hill.
Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill.
Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.
Web Links
http://msdn.microsoft.com/en-us/library/wcz57btd(v=vs.80).aspx
http://www.learncpp.com/cpp-tutorial/117-multiple-inheritance/
https://www.codecademy.com/learn/learn-c-plus-plus
Objectives
After studying this unit, you will be able to:
Introduction
A C++ control statement redirects the flow of a program in order to execute additional code. These
statements come in the form of conditionals (if-else, switch) and loops (for, while, do-while). Each
of them relies on a logical condition that evaluates to a Boolean value in order to run one piece of
code over another.
if statement
if-else statement
nested if statements
switch statement
If statement
The if statement consists a condition which is followed by one or some of the statements, if the
condition is true then the statements will be executed or else not. This statement is the simple and
easy decision control statement.
Syntax
Lab Exercise
#include<iostream>
Using namespacestd;
int main()
{ int a = 10;
if (a > 20)
{
cout<<"10 is less than 20";
}
cout<<"Out of if block";
}
if-else statement
In the if-else statement the if statement is followed by the else statement which will execute when
the expression is false.
Syntax
if (condition)
{ //statement will execute if the condition is true
}
else
{ //statement will execute if the condition is false
}
Lab Exercise
#include<iostream>
using namespace std;
int main(){
int a=10,b=20;
if(a>b)
{
cout<<"a is greater than b";
}
else
{
cout<<"b is greater than a";
}
}
Lab Exercise
#include <iostream>
using namespace std;
int main()
{
int a;
cout<< "Enter a number" << '\n';
cin>>a;
if(a>=10)
{
if(a>=20)
{
if(a>=100)
{
cout<<"You entered a value greater than 100." << '\n';
}
if(a<=75)
{
cout<<"You entered a value less than 75" << '\n';
}
}
if(a<=30)
{
switch statement
You can use the switch statement when you want to evaluate a condition against different cases
(expressions). Depending on the input, the appropriate case will be executed, and the result will be
printed. The syntax of switch case statement will be:
switch (condition)
{
case expression1:
//statement to execute;
break;
case expression2:
//statement to execute;
break;
case expression3:
//statement to execute;
break;
…
default:
// statement to execute;
}
Lab Exercise
#include <iostream>
using namespace std;
int main()
{
int a;
cout<< "Enter a number between 1 to 7 : " << '\n';
cin>>a;
switch (a)
{
case 1:
{
cout<< "The first colour of the rainbow is VIOLET: " << '\n';
break;
for loop
while loop
Notes
Aloop has four elements that have different purposes. These elements areas:
Initialization Expression(s)
Test Expression
Update Expression(s)
Loop's Body
for loop
The for loop is one of the most widely used loops in C++. The for loop is a deterministic loop in
nature, that is, the number of times the body of the loop is executed is known in advance.
Syntax
For(initialization expression(s); test-expression; update expression(s))
{
body-of-the-loop;
}
Lab Exercise
#include<iostream>
using namespace std;
int main (){
int n=0;
for (n=1; n<=10; n++)
cout<<n<<" ";
return 0;
}
Output:
while loop
The second loop available in C++ is the while loop. The while loop is an empty-controlled loop.
Syntax
While(expression)
{
loop-body;
}
Lab Exercise
#include<iostream>
do-while loop
Unlike the for and while loops, the do-while is an exit-controlled loop i.e., it evaluates its test-
expression at the bottom of the loop after executing its loop-body statements. This means that a do-
while loop always executes at least once.
Syntax
do
{
statement ;
}while(test-expression);
Lab Exercise
#include<iostream>
using namespacestd;
int main(){
int n=0;
do{
n++;
cout<<n<<" ";
}
while(n<10);
return 0;
}
Output
goto statement
break statement
continue statement
goto statement
The goto statement is a control statement which is used to transfer the control from one place to
another place without any condition in a program.
Lab Exercise
#include<iostream>
using namespacestd;
int main(){
int n=0;
while(n<10){
if(n==4)
gotox;
n++;
cout<<n<<" ";
}
x:
cout<<"Hello Label";
return 0;
}
Output
break statement
Lab Exercise
#include<iostream>
using namespace std;
int main(){
int n=0;
while(n<10){
if(n==4)
break;
n++;
cout<<n<<"";
}
return 0;
}
Output:
continue statement
The continue statement works somewhat like the break statement. Instead of forcing termination,
however, continue forces the next iteration of the loop to take place, skipping any code in between.
Syntax
continue;
#include <iostream>
using namespace std;
int main () {
int a = 5;
do {
if( a == 10) {
a =a+1;
continue;
}
cout<< "value of a: " << a <<endl;
a = a + 1;
}
while( a< 20 );
return 0;
}
Output:
Summary
Selection structures are implemented using If , If Else and Switch statements.
Looping structures are implemented using While, Do While and For statements.
The statements given as "initialization statements" are executed only once, at the beginning of
a for loop.
There are 3 statements given to a for loop as shown. One for initialization purpose, other for
condition testing and last one for iterating the loop. Each of these 3 statements are separated
by semicolons.
The C++ language provides a set of control statements that allows you to conditionally control
data input and output. These controls are referred to as loops.
Keywords
If statement - The single if statement in C++ language is used to execute the code if a condition is
true.
If-else statement - The if-else statement in C++ language is used to execute the code if the condition
is true or false. It is also called a two-way selection statement.
Switch Statement - Switch statement acts as a substitute for a long if-else-if ladder that is used to
test a list of cases.
SelfAssessment
1. Decision Control statements in C++ can be implemented using
A. if
B. if-else
C. Conditional Operator
D. All of the above
D. None of above
4. How many case statements are allowed before single break statement in switch statement?
A. 1
B. 2
C. Multiple
D. 100
6. B 7. D 8. A 9. D 10. C
Review Questions
1. What do you mean by nested if statement? Explain with suitable example.
2. What is difference between looping statements and jumping statements?
3. Write a program to reverse entered number.
4. What do you mean by switch statement? How it is different from if else statement.
5. Differentiate between while loop and do- while loop with suitable example.
Further Readings
E Balagurusamy; Object-oriented Programming with C++; Tata Mc Graw-Hill.
Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill.
Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.
Web Links
http://msdn.microsoft.com/en-us/library/wcz57btd(v=vs.80).aspx
http://www.learncpp.com/cpp-tutorial/117-multiple-inheritance/
https://www.codecademy.com/learn/learn-c-plus-plus
Objectives
After studying this unit, you will be able to:
Understand pointers
Recognize Structures
Analyze C structures
Introduction
A function is a programming unit with a unique name that may be identified. It can be invoked by
a programme once it has been defined. When called, it may accept zero or more inputs. The code
placed inside the function specification determines what should be done with the incoming
input(s). The function generates a single output after doing the given transformation. The caller of
the function receives this output.
Computers use their memory for storing instructions of the programs as well as the values of the
variables. Since memory is a sequential collection of storage cells each cell has an address
associated with it. Whenever we declare a variable, the system allocates, somewhere in the
memory, a memory location and a unique address is assigned to this location. Whenever a value is
assigned to this variable the value gets stored in the location having a unique address in the
memory associated with that variable. Therefore, the values stored in memory can be manipulated
using their addresses. Pointer is an extremely powerful mechanism to write efficient programs.
Incidentally, this feature makes C stand out as the most powerful programming language. Pointers
are the topic of this unit.
Example
#include<iostream.h>
Using namespace std;
void main()
{
cout<<"This is main function";
}
Parts Of Functions
1. Function Declaration
2. Function Call
3. Function Definition
Function Declaration
return_typefunction_name( param_1,param_2 ... param_n);
Example
intsum(intx,int y)
return_type
A function can return a value using the return statement to the main program. The function does
not return value if the return_type is void.
function_name
A function_name is a user-defined name (identifier) for calling/using the function. The function
name and the parameter list together constitute the function signature.
Function Call
When the main program is run, the program reaches the function call statement and invokes the
function and passes the control to it.
int main()
{
....
Function Definition
The actual function code block or function body is called as the function definition.
When the function call is triggered by the compiler, the program control is passed to the function
definition. Then the compiler executes statements in the body of the function and the program
control returns when the return statement or closing braces(}) is reached.
Example
#include<iostream>
using namespace std;
int add(int x,int y); // Function Declaration
int main() {
int a=100,b=100,c;
c = add(a,b); // Function Call
cout<<"Addition : "<<c;
}
int add(int x,int y) // Function Definition
{
int z;
z = x+y;
return z;
}
Pointer Declaration
Since pointer variables contain address that belongs to a separate data type, they must be declared
as pointers before we use them. Pointers can be declared just a any other variables. The declaration
of a pointer variable takes the following form:
data_type *pt_name;
The above statement tells the compiler three things about the variable pt_name.
1. The asterisk (*) tells that the variable pt_name is a pointer variable.
2. pt_name needs a memory location.
3. pt_name points to a variable of type data type.
: The statement
int *p;
declares the variable p as a pointer variable that points to an integer data type (int). The type int
refers to the data type of the variable being pointed to by p and not the type of the value of the
pointer.
Given below are some more examples of pointer declaration
Pointer Expression
Like other variables, pointer variables can be used in expressions. Arithmetic and comparison
operations can be performed on the pointers. For example, if p1 and p2 are properly declared and
initialized pointers, then following statements are valid.
y = *p1 * *p2; /multiply values stored in variables pointed to by *p1/and *p2
sum = sum + *p1; /increment sum by the value stored in the variable/pointed to by p1
The pointer may point to any location in the memory therefore you should be careful while using
pointers in your programs.
{
char name [30];
char author [25];
float price;
}
struct book book1, book2;
2. It is also allowed to combine structure declaration and variable declaration in one statement.
This declaration is given below:
struct person
{
char * name;
int age;
char *address;
}
p1, p2, p3;
While declaring structure variables along with their definition, the use of tag name is optional.
struct
{
char *name;
int age;
char *address;
}
p1, p2, p3;
Structure Initialization
A structure variable can be initialized as any other data type.
main( )
{
staticstruct
{
int weight;
float height;
}
student = {60, 180.75};
This assigns the value 60 to student. Weight and 180.75 student. Height. There is a one-to-one
correspondence between the members and their initializing values.
A structure must be declared as static if it is to be initialized inside a function (similar to arrays).
The following statements initialize two structure variables. Here, it is essential to use a tag
name.
main( )
{
structst_record
{
int weight;
float height;
}
staticstructst_recordstudent1 = {60, 180.75};
staticstructst_recordstudent2 = {53, 170.60};
------
-------
}
Another method is to initialize a structure variable outside the function as shown below:
structst_record / * No static word */
Limitations of C Structures
The struct data type cannot be treated like built-in data types.
Operators like + -, and others cannot be used on structure variables.
C Structures do not permit data hiding. Structure members can be accessed by any function,
anywhere in the scope of the Structure.
C structures do not permit functions inside Structure
C Programming language does not support access modifiers. So they cannot be used in C
Structures.
Structures in C cannot have constructor inside Structures.
Summary
In this unit, we learnt about “Functions”: definition, declaration, prototypes, types, function
calls datatypes and storage classes, types function invoking and lastly Recursion.
All these subtopics must have given you a clear idea of how to create and call functions from
other functions, how to send values through arguments, and how to return values to the
called function.
Structure is a derived data type used to store the instances of variables of different data types.
Structure definition creates a format that may be used to declare structure variables in the
program later on.
The structure operators like dot operator “.” are used to assign values to structure members.
Keywords
Data types: It refers to the type of information while storage class refers to the life-time of a
variable and its scope within the program.
Function Call: A function can be called by specifying its name followed by a list of arguments
enclosed in parentheses and separated by commas.
Return Statement: Information is returned from the function to the calling portion of the program
via return statement.
SelfAssessment
1. Which of the following is the default return value of functions in C++?
A. int
B. double
C. float
D. nothing
5. How many minimum numbers of functions are present in the C++ program?
A. 1
B. 2
C. 3
D. 0
C. zero
D. point to a type
11. A structure is a __
A. Collection of variables (different types) represented by single name.
B. A structure is a user defined data type in C
C. Keyword ‘struct’ is used to define structure in C
D. All of above
6. A 7. D 8. D 9. B 10. A
Review Questions
1. Explain the uses of pointers.
2. Discuss limitations of C structures in detail.
3. Write a program that demonstrates working of C structure.
4. What is function? Discuss advantages of using functions in OOP.
5. What do you mean by function prototyping?
Further Readings
E Balagurusamy; Object-oriented Programming with C++; Tata Mc Graw-Hill.
Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill.
Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.
Web Links
http://msdn.microsoft.com/en-us/library/wcz57btd(v=vs.80).aspx
https://www.codecademy.com/learn/learn-c-plus-plus
Objectives
After studying this unit, you will be able to:
Introduction
Classes and objects are at the core of object-oriented programming. Writing programs in
C++essentially means writing classes and creating objects from them. In this unit you will learn
towork with the same.
It is important to note the subtle differences between a class and an object, here. A class is atemplate
that specifies different aspects of the object it models. It has no physical existence. Itoccupies no
memory. It only defines various members (data and/or methods) that constitute theclass.
An object, on the other hand, is an instance of a class. It has physical existence and hence
occupiesmemory. You can create as many objects from a class once you have defined a class.
You can think of a class as a data type; and it behaves like one. Just as a data type like int, for
example, does not have a physical existence and does not occupy any memory until a variable
ofthat type is declared or created; a class also does not exist physically and occupies no
memoryuntil an object of that class is created.
Example
To understand the difference clearly, consider a class of vehicle and a fewobjects of this type as
depicted below:
In this example vehicle is a class while car, scooter and truck are instances of the class vehicle
andhence are objects of vehicle class. Each instance of the class vehicle – car, scooter and truck –
areallocated individual memory spaces for the variables – reg_no, no_wheels, fuel_type, makeand,
color – so that they all have their own copies of these variables.
1. Class declaration
2. Class function definitions
The class declaration describes the type and scope of its members. The class function
definitionsdescribe how the class functions are implemented. The general form of a class
declaration is:
class <class_name>
{
Private:
Variables declaration;
Function declarations;
Public:
Variable declaration;
function declarations;
};
The class declaration is similar to a struct declaration. The keyword class specifies that whatfollows
is an abstract data of type class_name. The body of a class is enclosed within braces andterminated
by a semicolon. The class body contains the declaration of variables and functions.
These functions and variables are collectively called members. They are usually grouped undertwo
sections, namely, private and public to denote which of the members are private and whichof them
are public. The keywords private and public are known as visibility labels.The members that have
been declared as private can be accessed only from within the class. Onthe other hand, public
members can be accessed from outside the class also. The data hiding(using private declaration) is
the key feature of object-oriented programming. The use of thekeyword private is optional. By
default, the members of a class are private. If both the labels aremissing, then, by default, all the
members are private. Such a class is completely hidden fromthe outside world and does not serve
any purpose.
The variables declared inside a class are known as data members and the functions are known as
member functions. Only the member functions can have access to the private data members and
private functions. However, the public members (both functions and data) can be accessed from
outside the class. The binding of data and functions together into a single class-type variable is
referred to as encapsulation. The access to private and public members of a class is well explained
diagrammatically in the Figure.
Let us consider the following declaration of a class for student:
class student
{
private:
int rollno;
char name [20];
public:
void getdata(void);
void disp(void);
};
The name of the class is student. With the help of this new type identifier, we can declare instances
of class student. The data members of this class are int rollno and char name [20]. The two function
members are getdata() and disp(). Only these functions can access the data members. Therefore,
they provide the only access to the data members from outside the class. The data members are
usually declared as private and member functions as public. The member functions are only
declared in the class. They shall be defined later.
A class declaration for a machine may be as follows:
class machine
{
int totparts, partno;
char partname [20];
public:
void getparts (void);
void disp(part_no);
};
Having defined the class, we need to create object of this class. In general, a class is a user
defineddata type, while an object is an instance of a class. A class provides a template, which
defines themember functions and variable that are required for objects of a class type. A class must
bedefined prior to the class declaration.
The general syntax for defining the object of a class is:
class <class_name>
{
private:
//data
// functions
public:
//functions
};
<class_name>object1, object2,…objectN;
where object1, object2 and objectN are the instances of the class <class_name>.
A class definition is very similar to a structure definition except the class definition defines
thevariables and functions.
The following program segment shows how a member function is declared outside the class
declaration.
class sample
{
private:
int x;
int y;
public:
int sum (); // member function declaration
};
int sample:: sum ( ) //member function definition
{
return (x+y);
}
Notes: The use of the scope operator double colon (::) s important for defining the member
functions outside the class declaration
They occupy space in memory that keeps its state and is operated on by the defined operations on
the object. Each object contains data and code to manipulate the data. Objects can interact without
having to know details of each other data or code.
callingof functions by value. The program declares a class integer representing a integer variable
x.Only the values of the objects are passed to the function written to swap them.
#include<iostream.h>
#include<conio.h>
class integer
{
int x;
public:
void getdata()
{
cout<< “Enter a value for x”;
cin>> x;
}
void disp()
{
cout<< x;
}
void swap(integer a1 , integer a2)
{
int temp;
temp = a2.x;
a2.x = al.x;
a1.x = temp;
}
};
main()
{
integer int1, int2;
int1.getdata();
int2.getdata();
cout<<“\n the value of x belonging to object int1 is “;
int1.disp();
cout<<“\n the value of x belonging to object int2 is “;
int2.disp();
integer int3; .
int3.swap(int1, int2); //int3 is just used to invoke the function
cout<<“ \nafter swapping “;
cout<<“\n the value of x belonging to object intI is “;
intl.disp();
cout<<“\n the value of x belonging to object int2 is “;
int2.disp() ;
cout<< “\n”;
getche();
}
You should get the following output.
Enter a value for x 15
Enter a value for x 50
the value of x belonging to object int is 15
the value of x belonging to object int2 is 50
after swapping
the value of x belonging to object int is 15
the value of x belonging to object int2 is 50
In the second method, the address of the object is passed to the function instead of a copy of
theobject. The called function directly makes changes on the actual object used in the call. As
againstthe first method any manipulations made on the object inside the function will occur in
theactual object.
void disp();
};
int counter::count = 0;
void counter::disp()
{
count++
cout<< “The present value of count is “ << count << “\n”;
}
main()
{
counter cntl ;
for(int i=0; i<5; i++)
cnt1.disp();
getche();
}
You should get the following output from this program.
The present value of count is 1
The present value of count is 2
The present value of count is 3
The present value of count is 4
The present value of count is 5
num1 = 2;
num2 = 3;
int sum = num1 + num2;
return sum;
}
};
int main()
{
Calculator obj;
int result = obj.add();
cout<< result;
return 0;
}
The class has two private members (properties) and one public member (method). In the
classdescription, the add() method uses the names of the private members as identifiers. So the
add()method, a member of the class has accessed the private members of the class.The main
function definition (second line) has been able to access the add() method of the classbecause the
add() method is public (it has a public access specifier).
The following code will not compile because the main function tries to access (use as identifier)a
private member of the class:
#include <iostream>
using namespace std;
class Calculator
{
private:
int num1;
int num2;
public:
int add()
{
num1; Notes
num2 = 3;
int sum = num1 + num2;
return sum;
}
};
int main()
{
Calculator obj;
obj.num1 = 2;
int result = obj.add();
cout<< result;
return 0;
}
The second line in the main function is wrong because at that line, main tries to access (use as
identifier) the private member, num1.
abovecode is OK.The following code will not compile, because line 2 in the main() function tries to
access aprotected member of the base class:
#include <iostream>
using namespace std;
class Calculator
{
protected:
int num1;
int num2;
};
class ChildCalculator: public Calculator
{
public:
int add()
{
num1;
num2 = 3;
int sum = num1 + num2;
return sum;
}
};
int main()
{
Calculator obj;
obj.num1 = 2;
ChildCalculatormyChildObj;
int result = myChildObj.add();
cout<<result;;
return 0;
}
An external function cannot access a protected member of a class (base class); however, a
derivedclass method can access a protected member of the base class.
Notes: A member of a class can access any member of the same class independent of the
whether the member is public, protected or private.
You should now know the role of the access specifiers: public, protected and private as appliedto
classes. In one of the following parts of the series, we shall see the role of the access specifiersin the
declaratory of a derived class.
A public member of a class is accessible by external functions and a derived class. A privatemember
of a class is accessible only by other members of the class; it is not accessible by externalfunctions
and it is not accessible by a derived class. A protected member of a class is accessibleby a derived
class (and other members of the class); it is not accessible by an external function.
Summary
A class represents a group of similar objects. A class in C++ binds data and
associatedfunctions together.
It makes a data type using which objects of this type can be created. Classes can representthe
real-world object which have characteristics and associated behavior.
While declaring a class, four attributes are declared: data members, member
functions,program access levels (private, public, and protected,) and class tag name.
While defining a class its member functions can be either defined within the class definitionor
outside the class definition. The public member of a class can be accessed outside theclass
directly by using object of this class type.
Private and protected members can be accessed with in the class by the member functiononly.
The member function of a class is also called a method. The qualified name of a classmember
is a class name: class member name.
A global object can be declared only from a global class whereas a local object can bedeclared
from a global as well as a local class.
The object is created separately to store their data members. They can be passed to aswell as
returned from functions. The ordinary member’s functions can access both static aswell as
ordinary member of a class.
Keywords
Class:Represents the real-world objects which have characteristics and associatedbehavior.
Global Class: A class whose definition occurs outside the bodies of all functions in a
program.Objects of this class type can be declared from anywhere in the program.
Local Class:A class whose definition occurs inside a function body. Objects of this class type canbe
declared only within the function that defines this class type.
Private Members: Class members that are hidden from the outside world.
Public Members: Class members (data members and member functions) that can be used by any
function.
SelfAssessment
1. Which of the following is correct about class?
A. Class can have member functions while structure cannot.
B. Class data members are public by default while that of structure are private.
C. Pointer to structure or classes cannot be declared.
D. Class data members are private by default while that of structure are public by default.
3. Which of the following OOP concept is not true for the C++ programming language?
5. How can static member function can be accessed directly in main() function?
A. Dot operator
B. Colon
C. Scope resolution operator
D. Arrow operator
8. What is the extra feature in classes which was not in the structures?
A. Member functions
B. Data members
C. Public access specifier
D. Static Data allowed
12. Which among the following feature does not come under the concept of OOPS?
A. Platform independent
B. Data binding
C. Data hiding
D. Message passing
13. The combination of abstraction of the data and code is viewed in________.
A. Inheritance
B. Class
C. Object
D. Interfaces
15. Which syntax among the following shows that a member is private in a class?
A. private::Name(parameters)
B. private: functionName(parameters)
C. private(functionName(parameters))
D. private functionName(parameters)
6. C 7. D 8. A 9. D 10. B
Review Questions
1. Define class. What is the difference between structures and classes in C++?
2. How can you pass an object of a C++ class to/from a C function?
3. Can a method directly access the non-public members of another instance of its class?
4. What’s the difference between the keywords struct and class?
5. Write a program to add two numbers defining a member getdata () and display () inside a
class named sum and displaying the result.
6. How does C++ help with the tradeoff of safety vs. usability?
7. “The main advantage of using a static member is to declare the global data which should be
updated while the program lives in memory”. Justify your statement.
8. Write a program to print the score board of a cricket match in real time. The display should
contain the batsman’s name, runs scored, indication if out, mode by which out, bowler’s score
(overs played, maiden overs, runs given, wickets taken). As and when a ball is thrown, the
score should be updated.
(print: Use separate arrays to store batsmen’s and bowler’s information)
9. If a member of a class is public, it can be accessed by an external function including a derived
class. Explain with an example.
10. Write a program in which a class has one private member (properties) and two public
member (method).
Further Readings
E Balagurusamy; Object-oriented Programming with C++; Tata Mc Graw-Hill.
Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill.
Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.
Web Links
http://msdn.microsoft.com/en-us/library/wcz57btd(v=vs.80).aspx
https://www.codecademy.com/learn/learn-c-plus-plus
Dr. Prikshat Kumar Angra, Lovely Professional University Unit 07: More on Classes and Objects
Objectives
After studying this unit, you will be able to:
● Understand function definition
● Analyze member functions
● Recognize private member functions
● Explain memory allocation of objects
● Analyze arrays with in class
Introduction
A class in C++ is the building block that leads to Object-Oriented programming. It is a user-defined
data type, which holds its own data members and member functions, which can be accessed and
used by creating an instance of that class. A C++ class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and brand
but all of them will share some common properties like all of them will have 4 wheels, Speed Limit,
Mileage range etc. So here, Car is the class and wheels, speed limits, mileage are their properties.
Lab Exercise:
#include<iostream>
using namespace std;
class find_sum{
public:
int x,y;
int sum();
};
int find_sum ::sum(){
return x+y;
}
int main(){
find_sumsum1;
sum1.x=100;
sum1.y=200;
cout<<"Sum of x and y is"<<sum1.sum();
return 0;
}
Output
Lab Exercise:
#include<iostream>
using namespace std;
class area{
private:
int l,w;
public:
void getdata();
void display_area();
};
void area::getdata()
{
cout<<"Enter length and width";
cin>>l>>w;
}
void area::display_area()
{
getdata();
cout<<"area is"<<l*w;
}
int main(){
area a1;
a1.display_area();
}
Output
Lab Exercise:
#include<iostream>
using namespace std;
class Box {
public:
double length;
void setWidth( double wid);
double getWidth( void );
private:
double width;
};
double Box::getWidth(void) {
return width ;
}
void Box::setWidth( double wid ) {
width = wid;
}
int main() {
Box box;
box.length = 5.0;
cout<< "Length of box : " <<box.length<<endl;
box.setWidth(5.0);
cout<< "Width of box : " <<box.getWidth() <<endl;
return 0;
}
Output
LabExercise
#include<iostream>
using namespace std;
int main(){
int arr[5];
cout<<"Enter Array Elements";
for(int i=0;i<=4;i++)
{
cin>>arr[i];
}
cout<<"Entered array elements are"<<endl;
for(int i=0;i<=4;i++)
{
cout<<arr[i]<<endl;
}
return 0;
}
Output
Lab Exercise:
#include<iostream>
using namespace std;
class student {
int marks[5];
public:
void getdata ();
void showdata();
};
void student::getdata(){
cout<<"Enter marks";
for(int i=0;i<=4;i++){
cin>>marks[i];
}
}
void student::showdata(){
cout<<"Marks are";
for(int i=0;i<=4;i++){
cout<<marks[i]<<endl;
}
}
int main(){
student stu;
stu.getdata();
stu.showdata();
}
Output
Example - To create three objects (s1, s2 and s3) for class ‘student’
Student s1, s2, s3;
#include <iostream>
using namespace std;
class student{
int roll_no;
char name[20];
int percentage;
public:
void setdata(){
cout<<"Enter Roll Number" ;
cin>>roll_no;
cout<<"Enter Name ";
cin>>name;
cout<<"Enter Percentage";
cin>>percentage;
}
void display(){
cout<<"\n Roll Number " <<roll_no<<" \tName " << name <<" \t Percentage " << percentage
<<endl;
}
};
int main(){
student s1,s2;
s1.setdata();
s2.setdata();
s1.display();
s2.display();
return 0;
}
Memory Allocation
• Many times, you are not aware in advance how much memory you will need to store
particular information in a defined variable and the size of required memory can be
determined at run time.
• You can allocate memory at run time within the heap for the variable of a given type using
a special operator in C++ which returns the address of the space allocated. This operator is
called new operator.
• If you are not in need of dynamically allocated memory anymore, you can usedelete
operator, which de-allocates memory previously allocated by new operator.
#include <iostream>
using namespace std;
class sample
{
public:
sample() {
cout<< "Constructor is called!" <<endl;
}
~sample() {
cout<< "Destructor is called!" <<endl;
}
};
int main( )
{
sample* obj = new sample[4];
delete [] obj; // Delete array of objects
return 0;
}
Output
Summary
A class represents a group of similar objects. A class in C++ binds data and associated functions
together.
It makes a data type using which objects of this type can be created. Classes can represent the
real-world object which have characteristics and associated behavior.
While declaring a class, four attributes are declared: data members, member functions, program
access levels (private, public, and protected,) and class tag name.
Keywords
Class: Represents the real-world objects which have characteristics and associated behavior.
Global Class: A class whose definition occurs outside the bodies of all functions in a program.
Objects of this class type can be declared from anywhere in the program.
Local Class: A class whose definition occurs inside a function body. Objects of this class type can be
declared only within the function that defines this class type.
Private Members: Class members that are hidden from the outside world.
Public Members: Class members (data members and member functions) that can be used by any
function.
SelfAssessment
1. What is the extra feature in classes which was not in the structures?
A. Member functions
B. Data members
C. Public access specifier
D. Static Data allowed
A. *
B. ( )
C. +
D. ::
A. class_name,function_name
B. return_type class_name :: member_function
C. datatype_class_name,function_name
D. class_name_function_name
6. Which among the following feature does not come under the concept of OOPS?
A. Platform independent
B. Data binding
C. Data hiding
D. Message passing
A. Inheritance
B. Class
C. Object
D. Interfaces
9. Which syntax among the following shows that a member is private in a class?
A. private ::Name(parameters)
B. private: functionName(parameters)
C. private(functionName(parameters))
D. private functionName(parameters)
A. Class
B. Constructor
C. Destructors
D. Attributes
A. :
B. ::
C. #
D. !!$
A. Class A { int a; };
B. Class B { }
C. Public class A { }
D. Object A { int y; };
14. A static member function can be called using the ………………… instead of its objects.
A. variable name
B. function name
C. Class name
D. object name
6. A 7. C 8. B 9. D 10. A
Review Questions
1. What do you mean by classes and objects in object-oriented programming?
2. Write a program that demonstrate working of member functions and classes.
3. Explain memory allocation of objects with the help of programing example.
4. Differentiate between public, private and protected access specifiers.
5. What is the significance of member functions, explain using an example.
Further Readings
E Balagurusamy; Object-oriented Programming with C++; Tata Mc Graw-Hill.
Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill.
Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia
Web Links
http://msdn.microsoft.com/en-us/library/wcz57btd(v=vs.80).aspx
https://www.codecademy.com/learn/learn-c-plus-plus
Dr. Prikshat Kumar Angra, Lovely Professional University Unit 08: Handling Functions
Objectives
After studying this unit, you will be able to:
Introduction
A function is a set of statements that are put together to perform a specific task. It can be statements
performing some repeated tasks or statements performing some specialty tasks like printing etc.
Code can be made simpler by using functions to divide it into smaller, more manageable chunks.
Using functions also save us from repeatedly writing the same code, which is another another
benefit. Instead of repeatedly writing the same set of statements, we only need to write one function
and then call it as and when necessary.
Library Functions
• It is already present inside the header file which we always include at the beginning of a
program.
• You just have to type the name of a function and use it along with the proper syntax.
User-defined Function
• User-defined function is a type of function in which we have to write a body of a function
and call the function whenever its require.
1. Function declaration
2. Function definition
3. Function call.
Function Declaration
A function declaration is also called a "Function prototype. “
we just specify the name of a function that we are going to use in our program like a variable
declaration.
Function Declaration
return_data_typefunction_name (data_type arguments);
Function Definition
• Function definition means just writing the body of a function.
• A body of a function consists of statements which are going to perform a specific task.
Function Definition
int sum(int a,int b)
{
int c;
c=a+b;
return c;
}
Function Call
• While creating a C++ function, you give a definition of what the function has to do. To use
a function, you will have to call or invoke that function.
• Call by value
• Call by reference
Call by value
• This method of passing arguments to a function copies the actual value of an argument
into the formal parameter of the function.
• By default, C++ uses call-by-value to pass arguments.
Lab Exercise:
#include<iostream>
using namespace std;
int sum(int x,int y)
{
return x+y;
}
int main(){
int a,b;
cout<<"Enter two numbers";
cin>>a>>b;
cout<<"Sum of entered number using call by value is = "<<sum(a,b);
return 0;
}
Output
Call by reference
This method copies the reference of an argument into the formal parameter. Inside the
function, the reference is used to access the actual argument used in the call. This means that
changes made to the parameter affect the argument.
Lab Exercise:
#include<iostream>
using namespace std;
int sum(int *x,int *y)
{
return *x+*y;
}
int main(){
int a,b;
cout<<"Enter two numbers";
cin>>a>>b;
cout<<"Sum of a and b is"<<sum(&a,&b);
return 0;
}
Output
Lab Exercise:
#include<iostream>
using namespace std;
class sample{
int x=10;
public:
void display(sample s){
cout<<"Value of x accessed by passing object is "<<s.x;
}
};
main(){
sample s1;
s1.display(s1);
}
Output
Summary
Each function puts related code together. This makes it easier for programmers to understand
code.
Functions make programming easier by eliminating code repetition.
Functions facilitate code reuse. You can call the same function to perform a task at different
sections of the program or even outside the program.
A function in C++ helps you group related code into one.
Functions facilitate code reuse.
Instead of writing similar code, again and again, you simply group it into a function. You can
then call the function from anywhere within the code.
Functions can be library or user-defined.
Library functions are the functions built-in various C++ functions.
To use library functions, you simply include its library of definition and call the function. You
don’t define the function.
Keywords
Function: A function is defined as a group of statements or a block of code that carries out specific
tasks.
Call by value: In this parameter passing method, values of actual parameters are copied to the
function’s formal parameters and the two types of parameters are stored in different memory
locations. So, any changes made inside functions are not reflected in the actual parameters of the
caller.
Call by reference: Both the actual and formal parameters refer to the same locations, so any
changes made inside the function are actually reflected in the actual parameters of the caller.
Self Assessment
A. Call by value
B. Call by reference
C. Both call by value and class by reference
D. Neither call by value nor call by reference
int z;
z=x+y;
A. formal Parameter
B. actual Parameter
C. intermediate
D. both A and B
A. Library functions
B. User define functions
C. Both Library functions and user define functions
D. None of above
A. Call by pointer
B. Call by value
C. Call by reference
D. None of the above
11. ______ symbol is used to pass the object by reference in OOP C++?
A. @
B. #
C. $
D. &
A. double quotes
B. single quotes
C. parenthesis
D. #@
#include<iostream>
class sample{
int x=10;
public:
cout<<s.x;
};
main(){
sample s1;
s1.display(s1);
A. 10
B. Error
C. 0
D. None of above
#include<iostream>
class sample{
int x=100;
public:
cout<<s.x;
};
main(){
sample s1;
s1.display();
A. Error
B. 10
C. 100
D. None of above
6. C 7. B 8. A 9. 10. B
Review Questions
1. What do you mean by function? Explain using a program example.
2. Write a program that demonstrates the concept of call by value.
3. Write a program that demonstrates the concept of call by reference.
4. Why do we need functions in OOP? Comment.
5. Explain default arguments.
Further Readings
E Balagurusamy; Object-oriented Programming with C++; Tata Mc Graw-Hill.
Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill.
Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.
Web Links
http://msdn.microsoft.com/en-us/library/wcz57btd(v=vs.80).aspx
https://www.codecademy.com/learn/learn-c-plus-plus
Dr. Prikshat Kumar Angra, Lovely Professional University Unit 09: More on Function
Objectives
After studying this unit, you will be able to:
● Understand the functions
● Describe the function overloading
● Explain the inline functions
● Understand friend function
● Analyze C++ Static Data Members & Functions
● Define polymorphism in C++
Introduction
A function is a code module that only does one thing. Sorting, searching for a specific item, and
inverting a square matrix are some instances. After a function is built, it is thoroughly tested.
Following that, it is added to the library of functions. A user can use a library function as often as
they like. This concept enhances software robustness while simultaneously shortening the time it
takes to develop code. System-defined and user-defined functions are the two types of functions.
A function is a group of statements that together perform a task. Every C++ program has at least
one function, which is main(), and all the most trivial programs can define additional functions.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
Caution: In case you design your main method in such a way that it must return a value to
the caller, then it must return an integer type value and therefore you must specify return type to be
int.
Library Functions
● It is already present inside the header file which we always include at the beginning of a
program.
● You just have to type the name of a function and use it along with the proper syntax.
User-defined Function
User-defined function is a type of function in which we have to write a body of a function and call
the function whenever it’s require.
1. Function Declaration: Function declaration also called a function prototype. We just specify
the name of a function that we are going to use in our program like a variable declaration.
Syntax:-
return_data_type function_name (data_type arguments);
2. Function Definition: Function definition function definition means just writing the body of a
function means we are just going to write the body of the function what kind of work we can do
with the function we are just write the logic they are a body of the function consists of the
statements, which are going to be perform a specific task like a sub routine or a sub program, it
is also known as the procedure we are writing the some of the lines there we are writing some
of the code there that is used to perform some of this specific task.
Function definition means just writing the body of a function. A body of a function consists of
statements which are going to perform a specific task. Let’s see definition of function is how
implemented using code.
Syntax:-
int sum(int a,int b)
{
int c;
c=a+b;
return c;
}
3. Function Call: While creating a C++ function, you give a definition of what the function has to
do. To use a function, you will have to call or invoke that function.
Function call has two methods.
3.1 Call by value
3.2 Call by reference
1. Call by value: This method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. By default, C++ uses call by value to
pass arguments.
2. Call by reference: This method copies the reference of an argument into the formal
parameter. Inside the function, the reference is used to access the actual argument used in
the call. This means that changes made to the parameter affect the argument.
Example
#include<iostream>
using namespace std;
int sum(int x,int y)
{
return x+y;
}
int main(){
int a,b;
cout<<"Enter two numbers";
cin>>a>>b;
cout<<"Sum of entered number using call by value is = "<<sum(a,b);
return 0;
}
Output
1. It also saves the overhead of push/pop variables on the stack when function is called.
2. Inline function may be useful (if it is small) for embedded systems because inline can yield
less code than the function call preamble and return.
Example
#include <iostream>
using namespace std;
inline int display_number(int n){
cout<<"Number is "<< n<<endl;
}
int main() {
display_number(50);
display_number(150);
display_number(200);
return 0;
}
Output
Example
#include <iostream>
using namespace std;
class demo {
public:
int n=100;
char ch='A';
void disp(demo d){
cout<<d.n<<endl;
cout<<d.ch<<endl;
}
};
int main() {
cout<<"Passing object to function"<<endl;
demo obj;
obj.disp(obj);
return 0;
}
Output
Syntax
class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}
Example
#include <iostream>
using namespace std;
class rectangle{
int a;
public:
friend void disp(rectangle r);
void get_length(int l);
};
void rectangle::get_length(int l){
a=l;
}
void disp( rectangle r){
cout<<"Entered length of rectangle is"<<r.a;
}
main(){
rectangle r;
r.get_length(10);
disp(r);
}
Output
Example
#include <iostream>
using namespace std;
class Demo
{
private:
static int a;
public:
static void fun()
{
cout <<"Value of a: " << a << endl;
}
};
int Demo :: a =500;
int main()
{
Demo obj;
obj.fun();
return 0;
}
Output
Polymorphism can be implemented using operator and function overloading, where the same
operator and function works differently on different arguments producing different results. These
polymorphisms are brought into effect at compile time itself, hence is known as early binding, static
binding, static linking or compile time polymorphism.
Now suppose we want the function to take float type argument then the function definition must
be changed as:
float sumfloat(float a, float b)
{
return (a + b);
}
As a matter of fact the function sum may take so many names as shown below.
int sumint(int a, int b)
{
return (a + b);
}
short sumshort(short a, short b)
{
return (a + b);
}
long sumlong(long a, long b)
{
return (a + b);
}
float sumdouble(double a, double b)
{
return (a + b);
}
This can be very tiring and extremely difficult to remember all the names. Function overloading is a
mechanism that allows a single function name to be used for different functions. The compiler does
the rest of the job. It matches the argument numbers and types to determine which functions is
being called. Thus we may rewrite the above listed functions using function overloading as:
int sum(int a, int b)
{
return (a + b);
}
float sum(float a, float b)
{
return (a + b);
}
short sum(short a, short b)
{
return (a + b);
}
long sum(long a, long b)
{
return (a + b);
}
float sum(double a, double b)
{
return (a + b);
}
Overloaded functions have the same name but different number and type of arguments. They can
differ either by number of arguments or type of arguments or both. However, two overloaded
function cannot differ only by the return type.
Example
#include<iostream>
using namespace std;
class sample{
public:
int chk_num(){
int a=10;
cout<<"Value of a is "<< a<<endl;
}
int chk_num(int a){
if(a%2==0)
cout<<"Number is even" << a <<endl;
else
cout<<"Number is odd" << a <<endl;
}
float chk_num(float x, float y)
{
cout<<"Sum of floating point number is "<< x+y<<endl;
}
};
main(){
sample obj;
obj.chk_num();
obj.chk_num(15);
obj.chk_num(15.12,25);
Output
Summary
An application written in C++ may have a number of classes. One of these classes must contain one
(and only one) method called main method. Although a private main method is permissible in C++
it is seldom used. For all practical purposes the main method should be declared as public method.
A function may take zero or more arguments when called. The number and type of arguments that
a function may take is defined in the function itself. If a function call fails to comply by the number
and type of argument(s), the compiler reports the same as error. When any program is compiled the
output of compilation is a set of machine language instructions, which is in executable program.
When a program is run, this complied copy of program is put into memory. C++ functions can
have arguments having default values. The default values are given in the function prototype
declaration. Prototype of a function is the function without its body. The C++ compiler needs to
about a function before you call it, and you can let the compiler know about a function is two ways
– by defining it before you call it or by specifying the function prototypes before you call it.
Keywords
Function: The best way to develop and maintain a large program is to divide it into several smaller
program modules of which are more manageable than the original program. Modules are written in
C++ as classes and functions. A function is invoked by a function call. The function call mentions
the function by name and provides information that the called function needs to perform its task.
Function Declaration: Statement that declares a function’s name, return type, number and type of
its arguments.
Function Overloading: In C++, it is possible to define several function with the same name,
performing different actions. The functions must only differ in their argument lists. Otherwise,
function overloading is the process of using the same name for two or more functions.
Function Prototype: A function prototype declares the return-type of the function that declares the
number, the types and order of the parameters, the function expects to receive. The function
prototype enables the compiler to verify that functions are called correctly.
Inline Function: A function definition such that each call to the function is, in effect, replaced by
the statements that define the function.
Self Assessment
1. Which of the following function / types of function cannot have default parameters?
A. Member function of class
B. Main()
C. Member function of structure
D. None of above
7. What are the two advantage of function objects than the function call?
A. It contains a state
B. It is a type
C. It contains a state & It is a type
D. It contains a prototype
12. Which is the correct syntax for declaring static data member?
A. static mamberName dataType;
B. dataType static memberName;
return X + Y;
return X + Y;
int main()
return 0;
A. 11 12.1
B. 12.1 11
C. 11 12
D. Compile time error
6. A 7. C 8. C 9. A 10. B
Review Questions
1. What is function prototyping? Why is it necessary? When is it not necessary?
2. What is purpose of inline function?
3. Differentiate between the following:
(a) void main()
(b) int main()
(c) int main(int argn, char argv[])
4. In which cases will declare a member function to be friend?
5. Write a program that uses overloaded member functions for converting temperature from
Celsius to Kelvin scale.
6. To calculate the area of circle, rectangle and triangle using function overloading.
7. Do inline functions improve performance?
8. How can inline functions help with the tradeoff of safety vs. speed?
9. Write a program that demonstrate working of function overloading.
10. Write a program that demonstrates working of inline functions.
Further Readings
● E Balagurusamy; Object Oriented Programming with C++; Tata Mc Graw-Hill.
● Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill. Robert Lafore;
● Object-oriented Programming in Turbo C++; Galgotia.
Web Links
● https://en.wikipedia.org/wiki/Object-oriented_programming
● www.web-source.net
● www.webopedia.com
Objectives
After studying this unit, you will be able to:
Introduction
A function is a code module that only does one thing. Sorting, searching for a specific item, and
inverting a square matrix are some instances. After a function is built, it is thoroughly tested.
Following that, it is added to the library of functions. A user can use a library function as often as
they like. This concept enhances software robustness while simultaneously shortening the time it
takes to develop code. System-defined and user-defined functions are the two types of functions.
A function is a group of statements that together perform a task. Every C++ program has at least
one function, which is main(), and all the most trivial programs can define additional functions.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
Syntax
Class class_name{
private:
static data_member;
public:
static return_typefunction_name()
{
//body
}
};
Example:
#include <iostream>
using namespace std;
class Demo
{
public:
static int n;
};
int Demo :: n =100;
int main()
{
cout<<"\nValue of n is: "<<Demo::n;
return 0;
}
Output
1. A static function can have access to only other static members (function or variable) declared
in the same class.
2. A static member function can be called using the class name (instead of its object) as follows-
Class_name::Function_name();
Example:
#include <iostream>
using namespace std;
class Demo
{
private:
static int a;
public:
static void fun()
{
cout<<"Value of a: " << a <<endl;
}
};
int Demo :: a =50;
int main()
{
Demo obj;
obj.fun();
return 0;
}
Output
10.3 Polymorphism
Polymorphism is an important OOP concept. Polymorphism means the ability to take more than
one form. For example, an operation may exhibit different behavior in different instances. The
behavior depends upon the types of data used in the operation. For example, consider the
operation of addition. For tow numbers, the operation will generate a sum. If the operands are
strings, then the operation will produce a third string by contention. The diagram given below,
illustrates that a single function name can be used to handle different number and types of
arguments. This is something similar to a particular word having several different meanings
depending on the context.
Polymorphism plays an important role in allowing objects having different internal structures to
share the same external interface. This means that a general class of operations may be accessed in
the same manner even though specific actions associated with each operation may differ.
Polymorphism is extensively used in implementing inheritance as shown below.
Polymorphism can be implemented using operator and function overloading, where the same
operator and function works differently on different arguments producing different results. These
polymorphisms are brought into effect at compile time itself, hence is known as early binding, static
binding, static linking or compile time polymorphism.
}
short sum(short a, short b)
{
return (a + b);
}
long sum(long a, long b)
{
return (a + b);
}
float sum(double a, double b)
{
return (a + b);
}
Overloaded functions have the same name but different number and type of arguments. They can
differ either by number of arguments or type of arguments or both. However, two overloaded
function cannot differ only by the return type.
Example:
#include<iostream>
using namespace std;
class sample{
public:
int chk_num(){
int a=10;
cout<<"Value of a is "<< a<<endl;
}
int chk_num(int a){
if(a%2==0)
cout<<"Number is even" << a <<endl;
else
cout<<"Number is odd" << a <<endl;
}
float chk_num(float x, float y)
{
cout<<"Sum of floating point number is "<<x+y<<endl;
}
};
main(){
sample obj;
obj.chk_num();
obj.chk_num(15);
obj.chk_num(15.12,25);
Output
Inheritance Polymorphism
Summary
Polymorphism is the occurrence of two or more distinct variants of a plant in the same
ecosystem together in such quantities that the rarest of them cannot be preserved by
repeated mutation.
If there are even a few percent of a population with a genetically regulated type, it may
have been preferred by option.
Polymorphism may either be intermittent, in which a chromosome is in the process of
rollout to an unopposed inhabitant, or regulated, in which the equilibrium of selective
agencies is retained at a fixed stage.
In general, due to the repeated creation of the variation, intermittent polymorphism is due
to environmental changes that make the results of an earlier disadvantageous
chromosome advantageous.
Keywords
Function: The best way to develop and maintain a large program is to divide it into several smaller
program modules of which are more manageable than the original program. Modules are written in
C++ as classes and functions. A function is invoked by a function call. The function call mentions
the function by name and provides information that the called function needs to perform its task.
Function Declaration: Statement that declares a function’s name, return type, number and type of
its arguments.
Function Overloading: In C++, it is possible to define several function with the same name,
performing different actions. The functions must only differ in their argument lists. Otherwise,
function overloading is the process of using the same name for two or more functions.
Function Prototype: A function prototype declares the return-type of the function that declares the
number, the types and order of the parameters, the function expects to receive. The function
prototype enables the compiler to verify that functions are called correctly.
SelfAssessment
class Demo
private:
static int a;
public:
cout<< a <<endl;
};
int main()
Demo obj;
obj.fun();
return 0;
A. 0
B. 20
C. Error
D. None of above
D. None of above
return X + Y;
return X + Y;
int main()
return 0;
A. 11 12.1
B. 12.1 11
C. 11 12
D. Compile-time error
A. Inheritance
B. Encapsulation
C. Polymorphism
D. None of the above
15. Several functions of the same name can be defined, as long as they have different
parameters, this is called
A. Function overloading
B. Functions reusing
C. Operators overloading
D. None of them
1. C 2. A 3. A 4. D 5. D
6. B 7. A 8. C 9. C 10. D
Review Questions
1. Program to demonstrate working static data members and static member functions in
object-oriented programming C++.
2. To calculate the area of circle, rectangle, and triangle using function overloading.
3. Do inline functions improve performance?
4. How can inline functions help with the tradeoff of safety vs. speed?
5. Write a program that demonstratesthe working of function overloading.
6. Write a program that demonstrates the working of inline functions.
Further Readings
E Balagurusamy; Object-oriented Programming with C++; Tata Mc Graw-Hill.
Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill.
Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia
Web Links
http://msdn.microsoft.com/en-us/library/wcz57btd(v=vs.80).aspx
https://teachcomputerscience.com/polymorphism/
https://www.codecademy.com/learn/learn-c-plus-plus
Dr. Prikshat Kumar Angra, Lovely Professional University Unit 11: Constructors and Destructors
Objectives
After studying this unit, you will be able to:
Introduction
When an object is created all the members of the object are allocated memory spaces. Each object
has its individual copy of member variables. However, the data members are not initialized
automatically. If left uninitialized these members contain garbage values. Therefore, it is important
that the data members are initialized to meaningful values at the time of object creation.
Conventional methods of initializing data members have lot of limitations. In this unit you will
learn alternative and more elegant ways initializing data members to initial values.
When a C++ program runs it invariably creates certain objects in the memory and when the
program exits the objects must be destroyed so that the memory could be reclaimed for further use.
C++ provides mechanisms to cater to the above two necessary activities through constructors and
destructors methods.
Notes:Constructor has the same name as the class. Constructor is public in the class.
Constructor does not have any return type.
While writing a constructor function the following points must be kept in mind:
1. The name of constructor method must be the same as the class name in which it is defined.
2. A constructor method must be a public method.
3. Constructor method does not return any value.
4. A constructor method may or may not have parameters.
Let us examine a few classes for illustration purpose. The class abc as defined below does not have
user defined constructor method.
classabc
{
}
main()
{
}
intx,y;
abcmyabc;
…;
The main function above an object named myabc has been created which belongs to abc class
defined above. Since class abc does not have any constructor method, the default constructor
method of C++ will be called which will initialize the member variables as:
myabc.x=0 and myabc.y=0.
Let us now redefine myabc class and incorporate an explicit constructor method as shown
below:
classabc
Observed that myabc class has now a constructor defined to except two parameters of integer type.
We can now create an object of myabc class passing two integer values for its construction, as listed
below:
main()
{
abcmyabc(100,200);
———;
}
intx,y; public:
abc();
abc(int);
abc(int, int);
abc::abc()
x=100; y=200;
}
abc::abc(int a)
x=a; y=200;
}
abc::abc(int a)
x=100;
y=a;
}
Class myabc has three constructors having no parameter, one parameter and two parameters
respectively. When an object to this class is created depending on number of parameters one of
these constructors is selected and is automatically executed.
Types of constructor
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
Destructor
Destructors are typically used to de-allocate memory. Also, they are used to clean up for objects
and class members when the object gets terminated.
When should you define your own destructor function? In many cases you do not need a
destructor function. However, if your class created dynamic objects, then you need to define your
own destructor in which you will delete the dynamic objects. This is because dynamic objects
cannot be deleted on their own. So, when the object is destroyed, the dynamic objects are deleted by
the destructor function you define.
class Calculator
{
public:
int *num1;
int *num2;
*num2 =ident2;
~Calculator()
{
delete num1;
delete num2;
}
int add(){
int sum=*num1+*num2;
return sum;
}
};
int main()
{
Calculator myObject(20,20);
int result = myObject.add();
cout<< result;
return 0;
}
The destructor function is automatically called, without you knowing, when the program no longer
needs the object. If you defined a destructor function as in the above code, it will be executed. If you
did not define a destructor function, C++ supplies you one, which the program uses unknown to
you. However, this default destructor will not destroy dynamic objects.
Output:-
Constructor called
Constructor called
Destructor called
Destructor called
Constructors Destructors
The constructor initializes the class and allots If the object is no longer required, then
the memory to an object. destructors demolish the objects.
They are often called in successive order. They are often called in reverse order of
constructor.
{
x=a.x;
y=a.y;
}
Suppose we create an object myabc1 with two integer parameters as shown below:
abc myabc1(1,2);
Having created myabc1, we can create another object of abc type, say myabc2 from myabc1, as
shown below:
myabc2=abc(& myabc1);
The data values of myabc1 will be copied into the corresponding data variables of object myabc2.
Another way of activating copy constructor is through assignment operator. Copy constructors
come into play when an object is assigned another object of the same type, as shown below:
abc myabc1(1,2);
abc myabc2;
myabc2=myabc1;
Actually assignment operator(=) has been overloaded in C++ so that copy constructor is invoked
whenever an object is assigned another object of the same type.
(a) If a new object has to be created before the copying can occur, the copy constructor
isused.
(b) Ifanewobjectdoesnothavetobecreatedbeforethecopyingcanoccur,theassignment
operator isused.
Example:-
#include <iostream.h>
#include <conio.h>
classdyncons
{
int * p;
public:
dyncons()
{
p=new int;
*p=100;
}
dyncons(int v)
{
p=new int;
*p=v;
}
int dis()
{
return(*p);
}
};
int main()
{
clrscr();
dyncons o, o1(90);
cout<<"The value of object o's p is:";
cout<<o.dis();
cout<<"\nThe value of object 01's p is:"<<o1.dis();
return 0;
}
Output:
The value of object o's p is:100
The value of object 01's p is:90
Lab Exercise
//# Program – Default constructor
#include<iostream>
using namespace std;
class constructor{
private:
intx,y;
public:
constructor(){
x=10;
y=90;
cout<<"Sum of x and y is :"<<x+y;
}
};
int main(){
constructor c;
return 0;
Output
Lab Exercise
// Program –Parameterizedconstructor
#include<iostream>
using namespace std;
class constructor{
private:
intx,y;
public:
constructor(inta,int b){
x=a;
y=b;
cout<<"Sum of x and y is :"<<x+y;
}
};
int main(){
constructor c(15,52);
return 0;
}
Output
Lab Exercise
// Program – Copy Constructor
#include<iostream>
using namespace std;
classcopyconstructor
{
private:
int x, y;
void display()
{
cout<<x<<" "<<y<<endl;
}
};
int main()
{
copyconstructor obj1(10, 15);
copyconstructor obj2 = obj1;
cout<<"Constructor : ";
obj1.display();
cout<<"Copy constructor : ";
obj2.display();
return 0;
}
Output
Lab Exercise
// Program – Dynamic Constructor
#include <iostream>
using namespace std;
class demo {
int* p;
demo(int a)
{
p = new int;
*p = a;
}
Output
While creating the object, arguments must be passed to let compiler know, which
constructor needs to be called.
//Program
#include<iostream>
using namespace std;
class demo{
intx,y;
public:
demo(){
x=10;
cout<<"X is ="<<x<<endl;
}
demo(inta,int b){
x=a;
y=b;
cout<<"Sum of x and y is"<<x+y;
}
};
main(){
demo d1,d2(90,59);
}
Output
11.8 Destructors
Constructors create an object, allocate memory space to the data members and initialize the data
members to appropriate values; at the time of object creation. Another member method called
destructor does just the opposite when the program creating an object exits, thereby freeing the
memory.
A destructive method has the following characteristics:
1. Name of the destructor method is the same as the name of the class preceded by a tilde (~).
2. The destructor method does not take any argument.
3. It does not return any value.
The following codes snippet shows the class student with the destructor method;
Example
#include <iostream>
using namespace std;
class student
{
public:
student()
{
cout<<"Constructor Invoked"<<endl;
}
~student()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main()
{
student s1;
return 0;
}
Summary
A constructor is a member function of a class, having the same name as its class and which
is called automatically each time an object of that class it created.
It is used for initializing the member variables with desired initial values. A variable
(including structure and array type) in C++ may be initialized with a value at the time of
its declaration.
The responsibility of initialization may be shifted, however, to the compiler by including a
member function called constructor.
A class constructor, if defined, is called whenever a program created an object of that class.
Constructors are public member unless otherwise there is a good reason against.
A constructor may take argument (s). A constructor may take no argument(s) is known as
default constructor.
A constructor may also have parameter (s) or argument (s), which can be provided at the
time of creating an object of that class.
C++ classes are derived data types and so they have constructor (s). Copy constructor is
called whenever an instance of same type is assigned to another instance of the same class.
If a constructor is called with a smaller number of arguments than required an error
occurs. Every time an object is created its constructor is invoked.
The functions that is automatically called when an object is no more required is known as
destructor. It is also a member function very much like constructors but with an opposite
intent.
SelfAssessment
1. Which of the followings is/are automatically added to every class, if we do not write our
own?
A. Copy Constructor
B. Assignment Operator
C. A constructor without any parameter
D. All of the above
class Point {
};
int main()
Point t1;
return 0;
A. Compiler Error
B. Runtime Error
C. Constructor called
D. None of Above
class demo{
public:
sum(inta,int b){
cout<<a+b;
};
main(){
demo d1;
d1.sum(d1.f_num=10,d1.s_num=20);
return 0;
A. 49
B. 50
C. 30
D. 10
10. Does constructor overloading include different return types for constructors to be
overloaded?
A. Yes, if return types are different, signature becomes different
B. Yes, because return types can differentiate two functions
C. No, return type can’t differentiate two functions
D. No, constructors doesn’t have any return type
12. Which is executed automatically when the control reaches the end of the class scope?
A. Constructor
B. Destructor
14. A destructor is used to destroy the objects that have been created by a ………………..
A. Class
B. Object
C. Constructor
D. Destructor
15. ……………….. Provides the flexibility of using different format of data at runtime
depending upon the situation.
A. Dynamic initialization
B. Run time initialization
C. Static initialization
D. Variable initialization
6. A 7. B 8. C 9. C 10. D
Review Questions
1. Write a program to calculate prime number using constructor.
2. Is there any difference between obj x; and objx();? Explain.
3. Can one constructor of a class call another constructor of the same class to initialize the this
object? Justify your answers with an example.
4. Should my constructors use “initialization lists” or “assignment”? Discuss.
5. Explain constructor and different types of constructor with suitable example.
6. Write a program that demonstrate working of copy constructor.
7. What about returning a local variable by value? Does the local exist as a separate object, or
does it get optimized away?
Further Readings
E Balagurusamy; Object Oriented Programming with C++; Tata McGraw-Hill.
Herbert Schildt; The Complete Reference C++; Tata McGraw Hill. Robert Lafore;
Object-oriented Programming in Turbo C++; Galgotia.
Web Links
https://en.wikipedia.org/wiki/Object-oriented_programming
www.web-source.net
www.webopedia.com
Objectives
After studying this unit, you will be able to:
Introduction
When an object is created all the members of the object are allocated memory spaces. Each object
has its individual copy of member variables. However, the data members are not initialized
automatically. If left uninitialized these members contain garbage values. Therefore, it is important
that the data members are initialized to meaningful values at the time of object creation.
Conventional methods of initializing data members have lot of limitations. In this unit you will
learn alternative and more elegant ways initializing data members to initial values.
When a C++ program runs it invariably creates certain objects in the memory and when the
program exits the objects must be destroyed so that the memory could be reclaimed for further use.
C++ provides mechanisms to cater to the above two necessary activities through constructors and
destructors methods.
Example
#include<iostream>
using namespace std;
Default arguments are different from constant arguments as constant arguments can’t be changed
whereas default arguments can be overwritten if required.
Example
#include <iostream>
#include <string>
using namespace std;
class demo{
int a,b,c;
public:
demo(int x,int y, int z=0){
a=x;
b=y;
c=z;
}
void display_sum();
};
void demo::display_sum(){
cout<<"Sum is "<< a+b+c <<endl;
}
int main() {
demo d(20,85);
demo d1(35,85,96);
d.display_sum();
Example
#include <iostream>
using namespace std;
class demo {
int* ptr;
public:
demo()
{
ptr = new int;
*ptr = 100;
}
void display()
{
cout << "Value in pointer: " << *ptr
<< endl;
}
};
int main()
{
demo* obj1 = new demo();
obj1->display();
delete obj1;
12.4 Destructor
Destructor is a member function which destructs or deletes an object.
It can be defined only once in a class. Like constructors, it is invoked automatically.
The following code illustrates the use of a destructor against dynamic objects:
#include <iostream>
using namespace std;
class Calculator
{
public:
int *num1;
int *num2;
Calculator(int ident1, int ident2)
{
num1 = new int;
num2 = new int;
*num1 =ident1;
*num2 =ident2;
}
~Calculator()
{
delete num1;
delete num2;
}
int add(){
int sum=*num1+*num2;
return sum;
}
};
int main()
{
Calculator myObject(20,20);
int result = myObject.add();
class A
{
// constructor
A()
{
cout << "Constructor called";
}
// destructor
~A()
{
cout << "Destructor called";
}
};
int main()
{
A obj1; // Constructor Called
int x = 1
if(x)
{
A obj2; // Constructor Called
} // Destructor Called for obj2
} // Destructor called for obj1
Output:-
Constructor called
Constructor called
Destructor called
Destructor called
Constructors Destructors
The constructor initializes the class and allots If the object is no longer required, then
When the object is created, a constructor is When the program gets terminated, the
called automatically. destructor is called automatically.
A constructor allows an object to initialize some A destructor allows an object to execute some
of its value before it is used. code at the time of its destruction.
When it comes to constructors, there can be When it comes to destructors, there is constantly
various constructors in a class. a single destructor in the class.
They are often called in successive order. They are often called in reverse order of
constructor.
Summary
A constructor is a member function of a class, having the same name as its class and which is
called automatically each time an object of that class it created.
It is used for initializing the member variables with desired initial values. A variable
(including structure and array type) in C++ may be initialized with a value at the time of its
declaration.
A constructor may take argument (s). A constructor may taking no argument(s) is known as
default constructor.
A constructor may also have parameter (s) or argument (s), which can be provided at the time
of creating an object of that class.
C++ classes are derived data types and so they have constructor (s). Copy constructor is called
whenever an instance of same type is assigned to another instance of the same class.
If a constructor is called with less number of arguments than required an error occurs. Every
time an object is created its constructor is invoked.
Keywords
Constructor: A member function having the same name as its class and that initializes class objects
with legal initial values.
Default Constructor: A constructor that takes no arguments.
Destructor: A member function having the same name as its class but preceded by ~ sign and that
reinitializes an object before it goes out of scope.
SelfAssessment
1. What are default arguments?
A. Arguments which are not mandatory to be passed
B. Arguments with default value that aren’t mandatory to be passed
C. Arguments which are not passed to functions
D. Arguments which always take same data value
2. The Constructors with all the default arguments are similar as default constructors. State
true or false.
A. True
B. False
C. May be
D. Can't say
cout<<"This is a constructor";
}
};
int main() {
C obj;
return 0;
}
A. This is a constructor
B. 0
C. 1
D. Compile time error
7. Which constructor function is designed to copy objects of the same class type?
A. Create constructor
B. Object constructor
C. Dynamic constructor
D. Copy constructor
8. Which is executed automatically when the control reaches the end of the class scope?
A. Constructor
B. Destructor
C. Overloading
D. Copy constructor
10. A destructor is used to destroy the objects that have been created by a ………………..
A. Class
B. Object
C. Constructor
D. Destructor
11. ……………….. Provides the flexibility of using different format of data at runtime
depending upon the situation.
A. Dynamic initialization
B. Run time initialization
C. Static initialization
D. Variable initialization
12. Destructors __________ for automatic objects if the program terminates with a call to
function exit or function abort
A. Are inherited
B. Are created
C. Are called
D. Are not called
13. Choose the right observation from following for the destructors concept?
A. Destructors can be overloaded
B. Destructors can have only one parameter at maximum
C. Destructors are always called after object goes out of scope
D. There can be only one destructor in a class
Answers forSelfAssessment
1. B 2. A 3. D 4. C 5. D
6. D 7. D 8. B 9. D 10. C
Review Questions
1. What do you mean by constructor?
2. What are used of destructor in program?
3. Differentiate between constructor and destructors.
4. Write a program that demonstrates working of default arguments.
5. What is destructor? Explain using program.
Further Readings
E Balagurusamy; Object Oriented Programming with C++; Tata Mc Graw-Hill.
Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill. Robert Lafore;
Object-oriented Programming in Turbo C++; Galgotia.
Web Links
https://en.wikipedia.org/wiki/Object-oriented_programming
www.web-source.net
www.webopedia.com
Objectives
After studying this unit, you will be able to:
Introduction
The ability to reuse code is a key element of OOP. The concept of reusability is highly supported in
C++. The C++ classes can be reused in a variety of ways. Other programmers can use a class once it
has been written and tested. The properties Notes of existing classes can be reused to create new
classes.
INHERITANCE is the process of creating a new class from an existing one. Because every object of
the defined class "is" also an object of the inherited class type, this is sometimes referred to as a "IS-
A" relationship. The previous class is known as the 'BASE' class, whereas the new class is known as
the 'DERIVED' class or sub-class.
Notes
The capability of a class to derive properties and characteristics from another class is called
Inheritance.
Inheritance is a process in which one object acquires all the properties and behaviours of its
parent object automatically
{
……
…… // members of derivedclass
}
The colon (:) indicates that the derivedclassname class is derived from the baseclassname class. The
access_specifier or the visibility mode is optional and, if present, may be public, private or
protected. By default it is private. Visibility mode describes the accessibility status of derived
features. For example,
class xyz //base class
{
//members of xyz
};
class ABC: public xyz //public derivation
{
//members of ABC
};
class ABC : XYZ //private derivation (by default)
{
//members of ABC
};
In inheritance, some of the base class data elements and member functions are inherited into the
derived class and some are not. We can add our own data and member functions and thus extend
the functionality of the base class.
1. Public Mode
2. Private Mode
3. Protected Mode
Public Mode
If we derive a sub class from a public base class. Then the public member of the base class will
become public in the derived class and protected members of the base class will become protected
in derived class.
Private Mode
If we derive a sub class from a Private base class. Then both public member and protected members
of the base class will become Private in derived class.
Protected Mode
If we derive a sub class from a protected base class. Then both public member and protected
members of the base class will become protected in derived class.
Single Inheritance
When a class inherits from a single base class, it is referred to as single inheritance.
Example
#include <iostream>
using namespace std;
class base
{
public:
int x;
void getdata()
{
cout<< "Enter the value of x = "; cin>> x;
}
};
class derive : public base
{
private:
int y;
public:
void readdata()
{
cout<< "Enter the value of y = "; cin>> y;
}
void product()
{
cout<< "Product = " << x * y;
}
};
int main()
{
derive a;
a.getdata();
a.readdata();
a.product();
return 0;
}
Output
Multiple Inheritance
When a class inherits from a two base classes, it is referred to as multiple inheritance.
Example
#include<iostream>
using namespace std;
class A
{
public:
int x;
void get_data()
{
cout<< "enter value of x: ";
cin>> x;
} };
class B
{ public:
int y;
void get_data1()
{
cout<< "enter value of y: "; cin>> y;
} };
class C : public A, public B
{
public:
void sum()
{
cout<< "Sum = " << x + y;
}
};
int main()
{
C obj;
obj.get_data();
obj.get_data1();
obj.sum();
return 0;
} //end of program
Output
Multilevel Inheritance
If a class is derived from another derived class then it is called multilevel inheritance.
Example
#include<iostream>
using namespace std;
class A{
public:
int marks;
void get_data(){
cout<<"Enter Marks";
cin>>marks;
}
};
class B:public A
{
public:
int show_data(){
cout<<"Entered Marks: " <<marks;
}
};
class C:public B{
};
main(){
C obj;
obj.get_data();
obj.show_data();
}
Output
Hierarchical Inheritance
Hierarchical inheritance is a kind of inheritance where more than one class is inherited from a
single parent or base class. Especially those features which are common in the parent class is also
common with the base class.
Example
#include<iostream>
using namespace std;
class A
{
public:
int x,y;
void get_data()
{
cout<< "Enter value of x: ";
cin>> x;
cout<<"Enter value of y: ";
cin>>y;
}
};
class B:public A
{
public:
void show_sum()
{
cout<< "Sum of x and y is : "<<x+y<<endl;
}
};
class C : public A
{
public:
void show_product()
{
cout<< "Product of x and y is : "<<x*y;
}
};
int main()
{ B obj1;
C obj2;
obj1.get_data();
obj1.show_sum();
obj2.get_data();
obj2.show_product();
return 0;
}
Output
Hybrid Inheritance
There could be situations where we need to apply two or more types of inheritance to design a
program. Basically Hybrid Inheritance is the combination of one or more types of the inheritance.
Here is one implementation of hybrid inheritance. Hybrid inheritance is combination of two or
more types of inheritance. It is also known as multipath inheritance.
Example
#include <iostream>
using namespace std;
class A
{
public:
int x;
};
class B : public A
{
public:
B()
{
x = 500;
}
};
class C
{
public:
int y;
C()
{
y = 100;
}
};
class D : public B, public C
{
public:
void sum()
{
cout<< "Sum= " << x + y;
}
};
int main()
{
D obj1;
obj1.sum();
return 0;
}
Output
Private derivation means that the base class has been inherited privately. Public members and
protected members of the base class are private within the derived class.Private members of the
base class stay private within the base class.
Syntax
class base_class_name
{
-----
-----
}
class derived_class_name : private base_class_name
{
----
----
}
// Program
#include<iostream>
using namespace std;
class emp{
private:
int id;
char name[10];
int salary;
void get_data(){
cout<<"Enter Id,Name and Salary of employee"<<endl;
cin>>id>>name>>salary;
}
public:
void disp(){
get_data();
cout<<"Details are"<<endl;
cout<<"Emp ID "<< id<<endl<<"Emp Name "<<name <<endl<<"Emp Salary "<<salary;
}
};
main(){
emp obj;
obj.disp();
}
Output
Summary
Inheritance is the capability of one class to inherit properties from another class.
It supports reusability of code and is able to simulate the transitive nature of real lifeobjects.
Inheritance has many forms: Single inheritance, multiple inheritance, hierarchical inheritance,
multilevel inheritance and hybrid inheritance.
A subclass can derive itself publicly, privately or protected. The derived class constructoris
responsible for invoking the base class constructor, the derived class can directly accessonly the
public and protected members of the base class.
When a class inherits from more than one base class, this is called multiple inheritance.
A class may contain objects of another class inside it. This situation is called nesting of objects and
in such a situation, the contained objects areconstructed first before constructing the objects of the
enclosing class.
Single Inheritance: Where a class inherits from a single base class, it is known as singleinheritance.
Multilevel Inheritance: When the inheritance is such that the class. A serves as a base classfor a
derived class B which is turn serves as a base class for the derived class C. This typeof inheritance is
called ‘Multilevel Inheritance.
Multiple Inheritance: A class inherit the attributes of two or more classes. This mechanism is known
as Multiple Inheritance.’
Hybrid Inheritance: The combination of one or more types of the inheritance.
Keywords
Abstract Class: A class serving only a base class for other classes and no objects of which are
created.
Base class:A class from which another class inherits. (Also called super class) Containership: The
relationship of two classes such that the objects of a class are enclosed within the other class.
Derived class:A class inheriting properties from another class. (also called sub class).
Inheritance:Capability of one class to inherit properties from another class.
Inheritance Graph:The chain depicting relationship between a base class and derived class.
Visibility Mode:The public, private or protected specifier that controls the visibility and
availability of a member in a class.
SelfAssessment
1. Inheritance allow in C++ program?
A. Class Re-usability
B. Creating a hierarchy of classes
C. Extendibility
D. All of above
3. A class can inherit properties of another class which is known as …………….. Inheritance.
A. Single
B. Multiple
C. Multilevel
D. Hierarchical
6. While inheriting a class, if no access mode is specified, then which among the following is
true in C++?
A. It gets inherited publicly by default
B. It gets inherited protected by default
C. It gets inherited privately by default
D. It is not possible.
D. None of above
11. All the classes must have all the members declared private to implement multilevel
inheritance.
A. True
B. False
C. Sometimes true, sometimes false
D. Always false
14. Which type of inheritance must be used so that the resultant is hybrid?
A. Multiple
B. Hierarchical
C. Multilevel
D. None of the above
15. What is the minimum number of classes to be there in a program implemented hybrid
inheritance?
A. 2
B. 3
C. 4
D. No limit
6. C 7. D 8. C 9. B 10. B
Review Questions
1. What do you mean by inheritance? Explain different types of inheritance with suitable
example.
2. Consider a situation where three kinds of inheritance are involved. Explain this situation with
an example.
3. What is the difference between protected and private members?
4. Scrutinize the major use of multilevel inheritance.
5. Discuss a situation in which the private derivation will be more appropriate as compared to
public derivation.
6. Write a C++ program to read and display information about employees and managers.
Employee is a class that contains employee number, name, address and department. Manager
class and a list of employees working under a manager.
7. Differentiate between public and private inheritances with suitable examples.
8. Explain how a sub-class may inherit from multiple classes.
9. What is the purpose of virtual base classes?
10. Write a C++ program that demonstrate working of hybrid inheritance.
Further Readings
E Balagurusamy; Object-oriented Programming with C++; Tata Mc Graw-Hill.
Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill.
Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.
Web Links
http://msdn.microsoft.com/en-us/library/wcz57btd(v=vs.80).aspx
http://www.learncpp.com/cpp-tutorial/117-multiple-inheritance/
Objectives
After studying this unit, you will be able to:
Introduction
Many real-life problems handle large volumes of data and, in such situations, we need to use some
devices such as floppy disk or hard disk to store the data. The data is stored in these devices using
the concept of files. A file is a collection of related data stored in a particular area on the disk.
Programs can be designed to perform the read and write operations on these files.
A program typically involves either or both of the following kinds of data communication:
We have already discussed the technique of handling data communication between the console
unit and the program. In this chapter, we will discuss various methods available for storing and
retrieving the data from files.
C++'s I/O system deals with file operations that are quite similar to console input and output
activities. As an interface between the applications and the files, it employs file streams. The input
stream is the one that provides data to the programme, while the output stream is the one that
receives data from the programme. To put it another way, the input stream pulls (or reads) data
from the file, whereas the output stream writes data to the file. Figure shows how this works.
The input operation entails establishing an input stream and connecting it to the programme and
the input file. Similarly, setting up an output stream with the appropriate linkages to the
programme and the output file is part of the output procedure.
Notes
Stream classes in C++ are used to input and output operations on files and i/o devices. These
classes have specific features and to handle input and output of the program.
The iostream.h library holds all the stream classes in the C++ programming language.
Files are dealt mainly by using three classes fstream, ifstream, ofstream.
ofstream:This Stream class signifies the output file stream and is applied to create files for writing
information to files
ifstream: This Stream class signifies the input file stream and is applied for reading information
from files
fstream: This Stream class can be used for both read and write from/to files.
Example
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
fstreamst;
st.open("test.txt",ios::out);
if(!st)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
st.close();
}
return 0;
}
Output
read(filename);
filename.close();
filename.open(“data2.dat”);
read(filename);
filename.close();
}
ifstreamfilename(char *fname, int open_mode);
The ifstream function Object() { [native code] } accepts two parameters in this form: a filename and
the mode in which the input file should be read. C++ has a variety of input file opening modes,
each of which provides distinct forms of reading control over the opened file. In C++, the file
opening modes are represented by an enumerated type called ios. Below is a list of the various file
opening modes.
The ifstream function Object() { [native code] } accepts two parameters in this form: a filename and
the mode in which the input file should be read. C++ has a variety of input file opening modes,
each of which provides distinct forms of reading control over the opened file. In C++, the file
opening modes are represented by an enumerated type called ios. Below is a list of the various file
opening modes.
OUTPUT
As stated earlier, for opening a file, we must first create a file stream and then link it to the
filename. A file stream can be defined using the classes ifstream, ofstream, and factream that are
contained in the header file fttream. The class to be used depends upon the purpose, that is,
whether we want to read data from the file or write data to it. A file can be opened in two ways:
As stated earlier, for opening a file, we must first create a file stream and then link it to the
filename. A file stream can be defined using the classes ifstream, ofstream, and fstream that are
contained in the header file fstream. The class to be used depends upon the purpose, that is,
whether we want to read data from the file or write data to it. A file can be opened in two ways:
1. Create a file stream object to manage the stream using the appropriate class. That is to say,
the class ofstream is used to create the output stream and the class ifstream to create the
input stream.
2. Initialize the file object with the desired filename.
For example, the following statement opens a file named "results" for output:
ofstreamoutfile("results"); // output only
This creates outfile as an ofstream object that manages the output stream. This object can be any
valid C++ name such as o_file, myfile or Pout. This statement also opens the file results and
attaches it to the output stream outfile. This is illustrated in Figure.
Similarly, the following statement declares infile as an ifstream object and attaches it to the file data
for reading (input).
ifstreaminfile("data"); // input only
The program may contain statements like:
outfile « "TOTAL.;
outfile « sum;
infile » number;
infile>> string;
Lab Exercise
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream of("demo.txt");
of<< "Writing to file using fstream constructor!" <<endl;
of.close ();
return 0;
}
Notes
The constructors of stream classes (ifstream, ofstream, or fstream) are used to initialize file
stream objects with the filenames passed to them.
Notes
If the situation requires simultaneous processing of two files, then you need to create a
separate stream for each file.
Lab Exercise
#include <iostream>
#include <fstream>
Lab Exercise
Lab Exercise
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ifstream is("demo.txt");
char c;
while (is.get(c))
cout<< c;
if (is.eof())
cout<< "EoF reached";
else
cout<< "error reading";
is.close();
return 0;
}
Output
Task
Write a program using C++ to demonstrate process of reading from file in C++.
Write a program using C++todemonstrate process of writing in file.
Summary
The C++ I/O system contains classes such as ifstream, ofstream and fatream to deal with file
handling. These classes are derived from fstreambase class and are declared in a header file
iostream.
A file can be opened in two ways by using the constructor function of the class and using the
member function open() of the class. While opening the file using constructor, we need to pass
the desired filename as a parameter to the constructor.
The open() function can be used to open multiple files that use the same stream object. The
second argument of the open() function called file mode, specifies the purpose for which the
file is opened.
If we do not specify the second argument of the open() function, the default values specified
in the prototype of these class member functions are used while opening the file. The default
values are as follows:
ios :: in — for ifstream functions, meaning-open for reading only.
ios :: out — for ofstream functions, meaning-open for writing only.
When a file is opened for writing only, a new file is created only if there is no file of that name.
If a file by that name already exists, then its contents are deleted and the file is presented as a
clean file.
To open an existing file for updating without losing its original contents, we need to open it in
an append mode.
The (stream class does not provide a mode by default and therefore we must provide the
mode explicitly when using an object of (stream class. We can specify more than one file
modes using bitwise OR operator while opening a file.
Keywords
ofstream:This Stream class signifies the output file stream and is applied to create files for writing
information to files
ifstream: This Stream class signifies the input file stream and is applied for reading information
from files
fstream: This Stream class can be used for both read and write from/to files.
File:A file is a collection of related data stored in a particular area on the disk.
eof():It returns non-zero when the end of file has been reached, otherwise it returns zero.
SelfAssessment
1. C++ uses <iostream.h> directive because
A. C++ is an object oriented language
B. C++ is a markup language
C. C++ does not have any input/output facility
D. All of the above
4. iostream is a subclass of
A. istream
B. instream
C. ostream
D. Both istream and ostream
9. Which of the following is the default mode of the opening using the ofstream class?
A. ios::in
B. ios::trunk
C. ios::out
D. ios::app
10. Which of the following is the default mode of the opening using the fstream class?
A. ios::in| ios::out
B. ios::trunk
C. ios::out
D. ios::in
11. “ios::app” causes all output to that file to be appended to the end. This value can be used
only with file capable of output.
A. True
B. False
12. The close() function is used to close a file,closed by disconnecting with its streaming.
A. True
B. False
6. A 7. B 8. C 9. C 10. A
Review Questions
1. What do you mean by C++ streams?
2. What are the uses of files in computer system and how data can be write using C++.
3. What are the steps involved in using a file in a C++ program.
4. What is a file mode? Describe the various file mode options available.
5. Describe the various approaches by which we can detect end of file condition successfully.
6. Write a C++ program to demonstrate working of detection of end of file in C++.
7. What are the advantages of files?
8. How can we open a file? Explain with suitable example.
9. Write full process with suitable C++ program for create a new file.
10. Explain file opening process in C++.
Further Readings
E Balagurusamy; Object-oriented Programming with C++; Tata Mc Graw-Hill.
Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill.
Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.
Web Links
https://study.com/academy/lesson/practical-application-for-c-plus-plus-
programming-working-with-files.html
https://www.codecademy.com/learn/learn-c-plus-plus
https://www.guru99.com/cpp-file-read-write-open.html