Lecture 13
Lecture 13
1
Lecture 1-2: Outline
• Concepts and Basics of C++ Programming
– Introduction
– What is Procedure Oriented Programming (POP)?
– What is Object Oriented Programming (OOP)?
• Differences between procedural and object oriented
programming
• Features of Input/output Streams
– Basic Input/Output in C++
– Stream class hierarchy
• Reading and writing data using cin and cout
• Structure of C++ program 2
Concepts and Basics of C++
Programming
3
Introduction
• C++ is an object oriented programming (OOP) language
developed by Bjarne Stroustrup.
• Stroustrup began developing C++ in 1979 (then called “C with
classes”), and, in his own words, invented C++, wrote its early
definitions, and produced its first implementation… choose and
formulated the design criteria for C++ , designed all its major
facilities.
• In 1983, “C with Classes” was renamed to “C++” (++ being the
increment operator in C), adding new features.
• First commercial release of the C++ language was in 1985.
4
What is Procedure Oriented Programming
(POP)?
• Procedure Oriented Programming language is a list of
instruction where each statement tells the computer to do
something.
• It focuses on procedure (function) & algorithm is needed to
perform the derived computation.
• When program become larger, it is divided into function &
each function has clearly defined purpose.
• Dividing the program into functions & module is one of the
cornerstones of structured programming.
• E.g.:- c, basic, FORTRAN.
5
Structure of Procedural Oriented
Programming
6
Relationships of data and function in
Procedural Programming
7
What is Object Oriented
Programming (OOP)?
• The major motivating factor in the invention of object oriented
approach is to remove some of the flaws encountered in the
procedural approach.
• OOP treats data as a critical element in the program
development and does not allow it to flow freely around the
system. It ties data more closely to the functions that operate
on it, and protects it from accidental modification from outside
functions.
• OOP allows decomposition of a problem into a number of
entities called objects and then builds data and functions
around these objects.
8
Organization of data and function in
OOP
9
Differences between procedural
and object oriented programming
10
Differences between procedural and
object oriented programming
However, to become proficient in the C ++ programming language, one
must first understand the fundamental differences between procedural
and object-oriented programming paradigms.
11
Differences between procedural and
object oriented programming
12
Differences between procedural and
object oriented programming
13
Differences between procedural and
object oriented programming
14
MCQ
15
Solution
16
Features of Input/output Streams
17
Features of Input/Output Streams
• C++ comes with libraries that provide us with many ways for
performing input and output.
• In C++ input and output are performed in the form of a sequence
of bytes or more commonly known as streams. There two types
of stream in C++.
– Input Stream: If the direction of flow of bytes is from the
device(for example, Keyboard) to the main memory then
this process is called input.
– Output Stream: If the direction of flow of bytes is
opposite, i.e. from main memory to device( display
screen ) then this process is called output.
18
Basic Input/Output in C++
19
Stream class hierarchy
20
Stream class hierarchy
• In the above figure, ios is the base class. The iostream class is derived
from istream and ostream classes.
• The ifstream and ofstream are derived from istream and ostream,
respectively. These classes handles input and output with the disk
files.The fstream.h header file contains a declaration of ifstream,
ofstream and fstream classes.
• The iostream.h file contains istream, ostream and iostream classes
and included in the program while doing disk I/O operations.
The filebuf class contains input and output operations with files.
• The streambuf class does not organize streams for input and output
operations, only derived classes of streambuf performs I/O operations.
• These derived classes arranges a space for keeping input data and for
sending output data.The istream and ostream invokes
the filebuf functions to perform the insertion or extraction on21 the
streams.
Stream class hierarchy
22
Header files available in C++ for Input –
Output operation are:
• iostream: iostream stands for standard input output stream.
This header file contains definitions to objects like cin, cout,
cerr etc.
• iomanip: iomanip stands for input output manipulators. The
methods declared in this files are used for manipulating
streams. This file contains definitions of setw, setprecision etc.
• fstream: This header file mainly describes the file stream. This
header file is used to handle the data being read from a file as
input or data being written into the file as output.
23
Stream Objects
• The standard C++ library defines the following stream objects
to access the standard sources and destinations of characters
during program execution.
• Cin: Standard input stream(usually the keyboard)
• Cout: Standard output stream(usually the screen)
• Cerr: Standard error stream, it is the same as the output
stream.
• Clog: Standard logging stream, it is the same as the output
stream.
24
Reading and writing data using cin
and cout
25
Cout
• cout is used for the output of data of various types. This has been
made possible by overloading the operator<<(insertion operator)
in the ostream class to recognize all the basic c++ types.
• eg. cout<<“Hello”;
cout will display this string as such on screen.
• eg. cout<< a;
• if “a’ is variable then cout can be used to display the contents
of “a”.
26
Example 1: To print the numbers and
character variables
#include<iostream>
Output:
using namespace std;
int main()
{
int num1=70;
double num2=256.783;
char ch='A';
cout<<num1<<endl;
cout<<num2<<endl;
cout<<"character:"<<ch<<endl;
}
Note:
•The endl manipulator is used to insert a new line. That's why each output is
displayed in a new line.
27
Cin
• Cin is used for the input of data of various types. This has been
made possible by overloading the operators >>(extraction) in the
istream class to recognize all the basic c++ types.
• The following is the general format for reading data from the
keyboard:
• eg: int a,b;
cin>>a>>b;
.
28
Example 2: Enter and Display Integer Value
#include<iostream>
Output:
using namespace std;
int main()
{
int num;
cout<<"Enter an integer:";
cin>>num;//Taking input
cout<<"The number is:"<<num;
}
Note: If we don't include the using namespace std; statement, we need to
use std::cin instead of cin .
29
Cascading of Input/Output Operators
• We can use the << operator multiple times in the same line.
This is called cascading. For example,
• Cout<<“\n”<<“First Name=“<<“Jian”;
30
MCQ 1
31
Solution
32
MCQ 2
33
Solution
34
MCQ 3
a. Operator
b. Functions
c. Objects
d. Data types
35
Solution
a. Operator
b. Functions
c. Objects
d. Data types
36
MCQ 4
37
Solution
38
MCQ 5
39
Solution
40
Structure of C++ Program
41
Structure of C++ Program
Section 1 : Header File
•The header files contain the definition of the functions and
macros we are using in our program. They are defined on the top
of the C++ program.
•In line #1, we used the #include <iostream> statement to tell
the compiler to include an iostream header file library which
stores the definition of the cin and cout methods that we have
used for input and output. #include is a preprocessor directive
using which we import header files.
Syntax:
•#include <library_name>
42
Structure of C++ Program
Section 2 : Global Declaration Section
•Global Variables are declared here.
•Global Declaration may include –
– Declaring Structure
– Declaring Class
– Declaring Variable
Section 3 : Class Declaration Section
•Actually this section can be considered as sub section for the
global declaration section.
•Class declaration and all methods of that class are defined here.
43
Structure of C++ Program
Section 4 : Main Function
•Each and every C++ program always starts with main function.
•This is entry point for all the function. Each and every method is
called indirectly through main.
•We can create class objects in the main.
•Operating system call this function automatically.
Section 5 : Method Definition Section
•This is optional section . Generally this method was used in C
Programming.
44
Program 1
// Program to add two numbers
#include <iostream>
Output:
using namespace std;
int main() {
int num1; //to store first number
cin>>num1;
add=num1+num2;
cout<<"Addition is: "<<add<<endl;
return 0; 45
}
Using namespace std
• A namespace is designed to overcome this difficulty and is
used as additional information to differentiate similar
functions, classes, variables etc. with the same name available
in different libraries. Using namespace, you can define the
context in which names are defined. In essence, a namespace
defines a scope.
• Therefore, Namespace collects identifiers used for class, object
and variables. NameSpace can be used by two ways in a
program, either by the use of using statement at the beginning,
like we did in above mentioned program or by using name of
namespace as prefix before the identifier with scope resolution
(::) operator.
Examples: std::cout << "A";
46
Using namespace std;
C++ practicing examples
47
Lecture 3
CSE202: OBJECT ORIENTED PROGRAMMING
48
Lecture 3: Outline
• Creating classes
• Class objects
• Accessing class members
49
Class and objects
• In C++, rather than creating separate variables and functions, we can
also wrap these related data and functions in a single place (by
creating objects).
• This programming paradigm is known as object-oriented
programming. But before we can create objects and use them in C+
+, we first need to learn about classes.
50
Class and objects
51
Class
• A class is a blueprint for the object. We can think of a class as a
sketch (prototype) of a house. It contains all the details about the
floors, doors, windows, etc. Based on these descriptions we build
the house. House is the object.
• 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..
53
Characteristics of a class
• The keyword class specifies abstract data type of type class
name.
• The body of a class is enclosed with in braces and terminated
by a semicolon.
• The functions and variables with in the class are collectively
called as members
• The members that have been declared as private can be
accessed only from within the class.
• Class definition is only a template and does not create any
memory space for a class.
• By default all the members are of type private .
54
Class Declaration
55
Scope resolution operator
• Scope resolution operator (::) is used to define a function outside a class or
when we want to use a global variable but also has a local variable with the
same name.
Example:
#include <iostream>
using namespace std;
char c = 'a'; // global variable
int main() {
char c = 'b'; //local variable
cout << "Local variable: " << c << "\n";
cout << "Global variable: " << ::c << "\n"; //using scope resolution operator
return 0;
56
}
Methods definition
• The member function of the class can be defined in two different
ways:
1) Inside the class definition: The member functions are simple
defined inside the class only i.e the body of the function resides
inside the range of class only.
2) Outside the class definition: by using scope resolution operator,
which specifies that the scope of the function is restricted to the
class class_name.
Syntax:- class_name:: function_name
57
Inside the class definition
Eg: class abc
{ cout<<“rollno=“;
private: cin>>rollno;
int rollno; }
char name[20]; void display()
public: {
void getdata() cout<<“name=“<<name;
{ cout<<“rollno=“<<rollno;
cout<<“name=“; }
cin>>name; };
58
Example:
Outside the class definition
cin>>name;
class abc
cout<<“rollno=“;
{
cin>>rollno;
private:
}
int rollno;
void abc :: display()
char name[20];
{
public:
cout<<“name and rollno=“;
void getdata();
cout<<name<<rollno;
void display();
}
};
void abc :: getdata()
{
cout<<“name=“;
59
Example
#include<iostream> void item :: getdata(int a, float b)
using namespace std; {
class item { number=a;
int number; cost=b;
}
float cost;
public:
int main()
void getdata(int a, float b); {
void putdata(void) item x;
{ cout<<"\n object x"<<"\n";
cout<<"number:"<<number<<"\n"; x.getdata(100, 299.95);
cout<<"cost:"<<cost<<"\n"; x.putdata();
} item y; Output:
}; cout<<"\n object y"<<"\n";
y.getdata(200, 175.50);
y.putdata();
return 0;
}
60
MCQ
What does your class can hold?
A. data
B. functions
C. both a & b
D. none of the mentioned
61
Solution
What does your class can hold?
A. data
B. functions
C. both a & b
D. none of the mentioned
62
Creating class objects
• Once a class has been declared, we can create variables of that
type by using the class name.
For example:
• item x;
• Creates a variable x of type item. In C++, the class variables
are known as objects. Therefore, x is called an object of item.
We may also declare more than one object in one statement.
Example:
• item x,y,z;
• The declaration of an object is similar to that of a variable of
any basic type. The necessary memory space is allocated to an
object at this stage.
63
Creating class objects
• Objects can also be created when a class is defined by placing
their names immediately after the closing brace, as we do in the
case of structures. For example:
class item
{
….……
….……
} x,y,z;
• Would create the objects x,y and z of type item. This practice is
seldom followed because we would like to declare the objects
close to the place where they are used and not at the time of
64
class definition.
More points
65
Memory allocation for objects
⮚ Actually, the member functions are created and placed in the
memory space only once when they are defined as a part of a class
specification.
⮚ Since all the objects belonging to that class use the same member
functions, no separate space is allocated for member functions when
the objects are created.
⮚ Only space for member variables is allocated separately for each
object.
⮚ Separate memory locations for the objects are essential, because the
member variables will hold different data values for different
objects.
66
Accessing a Data Member
Accessing a data member depends solely on the access control of
that data member. If its public, then the data member can be
easily accessed using the direct member access (.) operator with
the object of that class.
class A
{
public: Access Specifier : will discuss in
the next slide
int x;
Void func();
}obj1; 1st Method to declare object
main()
{
A obj2; 2nd Method to declare object
obj1.x=10;
obj2.x=20; Obj_name.Var1
obj1.func(); Obj_name.function()
Accessing data members using obj
--- 67
}
Access specifiers
There are 3 access specifiers for a class in C++.
•These access specifiers define how the members of the class can
be accessed.
•Of course, any member of a class is accessible within that class.
There are three types of access specifiers, they are:
1.Public
2.Private
3.Protected
68
Public
72
Protected
• Any member declared under this specifier is not accessible from outside
the class, by using the object of the class.
• The protected members of a class get inherited completely to the child
classes and they maintain their protected visibility in the child class.
• The protected members are accessible to only the member functions and
friend functions in the class.
Syntax:
Class definition
{
protected :
declarations or definitions
};
Example will discuss after MTT 73
Area of a circle
// C++ program to demonstrate public // C++ program to demonstrate private
// access modifier // access modifier
75
Solution
76
MCQ
77
Solution
78
Public Vs. Private
PUBLIC PRIVATE
The data members and member functions Only the member functions or the friend
declared public can be accessed by other functions are allowed to access the
classes too. private data members of a class.
79
MCQ
Find output:
class Circle {
int radius; a: 3.140000
float compute_area() b: 3.14
{ c: no output
d: error
radius=1;
return 3.14 * radius * radius;
}
};
int main()
{
Circle obj;
cout << "Area is: " << obj.compute_area();
return 0; 80
}
Solution
Find output:
class Circle {
int radius;
float compute_area() a: 3.140000
{ b: 3.14
c: no output
radius=1; d: error
return 3.14 * radius * radius;
} Note: Pvt.
member can’t
}; access outside
int main() the class
{
Circle obj;
cout << "Area is: " << obj.compute_area();
return 0;
} 81
Program 1: Basic_class_object
void sum()
#include<iostream> {
using namespace std; int z;
class abc z=x+y;
{ cout<<"The sum is:"<<z;
int x,y; }
public:
void getdata() };
{
cout<<"Enter the values of x and y:"<<endl;
cin>>x>>y; int main()
} {
abc obj1;
obj1.getdata();
obj1.sum();
}
82
Program 2: Basic_class_object
#include<iostream> int main()
using namespace std; {
class item item x;
{ cout<<"\nObject x="<<"\n";
int number; x.getdata(100,299.95);
float cost; x.putdata();
public:
void getdata(int a,float b) item y;
{ cout<<"\nobject y="<<"\n";
number=a; y.getdata(200,175.50);
cost=b; y.putdata();
} return 0;
//Defining member function inside class }
definition
void putdata(void)
{
cout<<"Number:"<<number<<"\
n";
cout<<"Cost:"<<cost<<"\n"; 83
}
Program 3: Arithmetic operations using
classvoid divide()
#include<iostream> {
using namespace std; int z;
class arithmetic z=x/y;
{ cout<<"Division is:"<<z;
int x,y; }
void multiply()
public:
{
void getdata() int z;
{ z=x*y;
cout<<"Enter the value of x and y:"<<endl; cout<<"Multiplication is:"<<z;
cin>>x>>y; }
} void subtract()
void sum() {
{ int z;
int z; z=x-y;
cout<<"Subtraction result is:"<<z;
z=x+y;
}
cout<<"Sum is:"<<z; }; 84
}
Program 3: Arithmetic operations using class
int main()
{
arithmetic obj1;
obj1.getdata();
obj1.sum();
obj1.subtract();
obj1.multiply();
obj1.divide();
}
85
Program 4:
Array of objects
#include<iostream>
#include<conio.h>
using namespace std; void employee::putdata(void)
class employee {
{ cout<<"\n Entered name is:"<<name;
char name[50]; cout<<"\n Entered age is:"<<age;
int age; }
public:
void getdata(void);
void putdata(void);
};
void employee::getdata(void)
{
cout<<"\n Enter the name of employee:";
cin>>name;
cout<<"\n Enter the age of employee:";
cin>>age;
} 86
Program 4:
Array of objects
const int size=3;
int main()
{
employee emp[size];
int i;
for(i=0;i<3;i++)
{
cout<<"\n Enter details of employee number"<<i+1;
emp[i].getdata();
}
for(i=0;i<3;i++)
{
cout<<"\nDetails of the employee number"<<i+1;
emp[i].putdata();
}
getch();
return 0;
} 87
C++ practicing examples
88