OOP Through C++ Notes - UNIT1
OOP Through C++ Notes - UNIT1
1
S.No. C C++
1 C is Procedure Oriented Programming C++ is Procedure Oriented
language Programming language and Object
Oriented Programming language.
6 In C In C++
• scanf() Function used for Input. • Cin>> Function used for Input.
• printf() Function used for output. • Cout<< Function used for output.
7 In C format specifiers are required to read In C++ format specifiers are not
and print the data. required to print or read the data.
8 C uses “stdio.h” header file for input and C++ uses “iostream” for the same
output oprations. purpose.
9 In C all variables are declared at the starting In C++ all variables are declared
of the scope. anywhere in the scope.
i.e.at the time of first use.
12 In C, malloc() and calloc() Functions are In C++, new and delete operators are
used for Memory Allocation and free() used for Memory Allocating and
function for memory Deallocating. Deallocating.
2
Class, Object, Encapsulation and Data
hiding, Inheritance, Polymorphism,
Abstraction and Message passing.
16 C++ does not support friend function and C++ supports friend function and virtual
virtual function. function.
18 C++ does not support constructors and C++ supports Constructors and
destructors. Destructors.
19 C++ does not Exception handling and C++ supports Exception handling and
Templates. Templates.
3
Disadvantages:
1. Large programs are divided into smaller programs known as functions. These functions can
call one another. Hence security is not provided.
2. No importance is given to security of data and importance is given to doing things.
3. Data move openly around the system from function to function.
4. Most functions accesses global data, what happens to the data is not known.
The Object-Oriented Technology/ Programming:
➢ The major motivating factor in the invention of object oriented approach is to remove
drawbacks of procedural oriented approach.
➢ OOP treats data as critical element in the program development and does not allow it
freely to flow around the system or application or program.
➢ OOP combines the data and functions into a single unit this process is called
encapsulation.
➢ The organisation of data and functions in object oriented programming is shown in the
following diagram.
➢ OOP allows divide a problem into a no of entities called as objects and then build data
and functions around these objects.
➢ The data of an object can be accessed only by the function associated with that object.
➢ In OOP, function of one object can access the function of other objects.
Basic Concepts (Key Concepts) of Object-Oriented Programming:
Object-Oriented Programming is a methodology or paradigm to design a program using
classes and objects.
It simplifies the software development and maintenance by providing some concepts:
➢ Class
➢ Object
➢ Encapsulation & Data hiding
➢ Inheritance
➢ Polymorphism
➢ Abstraction
➢ Message passing
4
Class:
Class is an abstract data type (user defined data type) that contains member variables (Data
members) and member functions that operate on data. It starts with the keyword class. A class
denotes a group of similar objects.
(Or)
Class is a blueprint or template for creating an object.
An object is an entity that exists physically in the real world which requires some memory is
called as an object.
e.g.: employee e1, e2;
In the above example employee is the class name and e1 and e2 are objects of that class.
e.g.: Class Object
5
Private data and functions are available to the public functions only. They cannot be accessed
by the other part of the program. This process of hiding private data and functions from the
other part of the program is called as data hiding
Example: capsule, it is wrapped with different medicines.
Inheritance:
➢ It is a process of using the properties (data members and member functions) of one class
inside other class.
➢ The main aim of Inheritance is Reusability of the data members and member functions i.e
data members and member functions declared in one class can be accessed by other class.
➢ In Inheritance, two classes are involved (super class/base class/parent class and sub
class/derived class/child class).
➢ The class which gives properties is called as super class / base class / parent class.
➢ The class which takes the properties is called as sub-class/derived class /child class.
Base Class
Derived Class
Reusability: Using the already existing code is called as reusability. This is mostly used in
inheritance. The already existing code is inherited to the new class. It saves a lot of time and
effort. It also reduces the size of the program.
Polymorphism:
The word polymorphism is derived from two latin words poly(many) and morph (forms).
Polymorphism means the ability to take many forms. Polymorphism allows to take different
implementations for same name.
Poly -> many
Morph -> forms
ism -> behaviours
There are two types of polymorphism, Compile time polymorphism and Run time
polymorphism.
In Compile time polymorphism binding is done at compile time and in runtime polymorphism
binding is done at runtime.
e.g.: Function overloading, operator overloading
6
Function Overloading:
Function overloading is a part of polymorphism. Same function name having different
implementations with different number and type of arguments.
Operator Overloading:
Operator overloading is a part of polymorphism. Same operator can have different
implementations with different data types.
e.g.: MouseClick()
Close button -> Window gets closed
Max button -> window gets maximised
Min button -> window gets minimized
Abstraction:
It is a process of Hiding internal details and showing functionality is known as abstraction.
They are divided into two types:
1.Functional Abstraction
2.Data Abstraction
Functional Abstraction:
Just making a call to a function not bothering how it has been implemented is call as Functional
Abstraction.
Data Abstraction:
Using a class without the knowledge of its implementation is called as Data Abstraction.
For example: phone call, we don't know the internal processing.
Message Passing:
An object-oriented program contains a set of objects that communicate with one another. The
process of object oriented programming contains the basic steps:
1. Creating classes
2. Creating objects
3. Establishing communication among objects
This communication is done with the help of functions (i.e., passing objects to functions)
Objects communicate with one another by sending and receiving information much the same
way as people pass messages to one another.
Message passing involves specifying the name of object, the name of the function (message)
and the information to be sent.
Example:
7
Advantages of OOP:
Object oriented technology provides many advantages to the programmer and the user. This
technology solves many problems related to software development, provides improved quality
and low cost software.
1. Object oriented programs can be comfortably upgraded.
2. Using inheritance, we can eliminate redundant program code and reuse already existing
code.
3. Data hiding facilitates the programmer to design and develop safe programs.
4. Through polymorphism, it provides the extensibility of the code.
5. With OOP, programs are easy to understand.
6. With OOP, programs are easier to test, manage and maintain.
7. Objects can communicate with each other by message passing mechanism.
Applications of OOP:
The promising areas for application of OOP includes:
1. Real-time systems
2. Simulation and modeling
3. Object-oriented databases
4. Hypertext, hypermedia and experttext
5. AI and expertsystems
6. Neural networks and parallel programming
7. Decision support and Automation system
8. CIM/CAM/CAD systems
Documentation Section
Linking Section
Definition Section
Global Declaration Section
Class Declaration Section
Class Member Functions Definitions Section
Main Function Section
Fig. Structure of a C++ program
Documentation Section:
1. This section comes first and it is also called as comments sections.
2. Comments are non-executable statements in any programming language.
3. Comments are used to write the program statement / program name.
e.g. /* Write a C++ program illustrating Checking whether the number is even or odd
using Ternary operator. */
8
4. Comments are used to write the program log.
e.g. /* Program Description : To check the no is even or odd
Created Date : 28/10/2021
Created Time : 10.00 am
Created by : ABC
*/
5. Comments are used to write the remarks for each line in the program.
6. Comments are two types
1.Single line Comments:
Single-line comments start with two forward slashes (//).
Example: // This is a comment
2. Multi line Comments:
Multi-line comments start with /* and ends with */.
Example: /* Write a C++ program illustrating Checking
whether the number is even or odd
using Ternary operator. */
7. Whatever written in the documentation section is the comment and is not compiled by
the compiler.
8. Documentation Section is optional since the program can execute without them.
Linking Section:
The linking section contains two parts:
1. Header Files
2. Namespaces
Header Files:
1. Generally, a program includes various programming elements like built-in functions,
classes, objects, keywords, constants, operators, etc. that are already defined in the
standard C++ library.
2. In order to use such pre-defined elements in a program, an appropriate header must be
included in the program.
3. Standard headers are specified in a program through the pre-processor
directive #include.
Example: #include<iostream>
4. When the compiler processes the instruction #include<iostream>, it includes the
objects (cout, cin, cerr & clog) of the stream in the program.
Namespaces:
1. A namespace permits grouping of various entities like classes, objects, functions, and
various C++ tokens, etc. under a single name.
2. Any user can create separate namespaces of its own and can use them in any other
program.
3. In the below snippets, namespace std contains declarations for cout, cin, endl, etc.
statements.
Example: using namespace std;
9
4. Namespaces can be accessed in multiple ways:
using namespace std;
using std :: cout;
Definition Section:
1. It is used to declare some constants and assign them some value.
Example: #define PI 3.14
In #define is a pre-processor directive which tells the compiler whenever the PI is found
replace it with 3.14.
2. It is used to define your own datatype using primitive data types.
Example: typedef int K;
This statement telling the compiler that whenever you will encounter K replace it by int
and as you have declared k as datatype you cannot use it as an identifier.
Global Declaration Section:
1. Here the variables, functions and the class definitions which are going to be used in the
program are declared to make them global.
2. The scope of the variable / function declared in this section continues until the entire
program terminates.
Example:
int a, b; // Global Delaration
int main ()
{
Statements;
}
Class Declaration Section:
This section contains declaration section of Class. You can declare a class and then declare
data members and member functions inside that class. You can also inherit one class from
another existing class in this section.
Example:
class Demo
{
int a, b;
public:
void input();
void output();
};
10
4. This section contains definition of the member functions that are declared inside the
class.
Example:
void Demo::input( )
{
cout <<” Enter value of a : “<<endl;
cin >> a;
cout <<” Enter value of b : “<<endl;
cin >> b;
}
11
Syntax:
#include <filename.h>
or
#include "filename.h"
// C++ program to find the sum of two numbers using function declared in header file
#include "iostream"
#include "sum.h" // Including header file
using namespace std;
int main()
{
int a = 13, b = 22; // Given two numbers
// Function declared in header file to find the sum
cout << "Sum is: "<< sumOfTwoNumbers(a, b)<< endl;
}
12
Basic input and output in C++:
• C++ I/O operation is using the stream concept. Stream is the sequence of bytes or flow
of data. It makes the performance fast.
• If bytes flow from main memory to device like printer, display screen, or a network
connection, etc, this is called as output operation.
• If bytes flow from device like keyboard, printer, display screen, or a network
connection, etc to main memory, this is called as input operation.
I/O Library Header Files
Let us see the common header files used in C++ programming are:
13
Header File Function and Description
<iostream> It is used to define the cout, cin and cerr objects, which correspond to
standard output stream, standard input stream and standard error stream,
respectively.
<iomanip> It is used to declare services useful for performing formatted I/O, such
as setprecision and setw etc.
(Or)
#include <iostream>
int main()
{
// prints the string enclosed in double quotes
std::cout << " Welcome to C++ Programming";
return 0;
}
Output:
Welcome to C++ Programming
#include <iostream>
using namespace std;
int main()
{
int num1 = 70;
double num2 = 256.783;
char ch = 'A';
cout << num1 << endl; // print integer
cout << num2 << endl; // print double
14
cout << "character: " << ch << endl; // print char
return 0;
}
Output:
70
256.783
character: A
int main()
{
int num;
cout << “Enter an integer: “;
cin >> num; // Taking input
cout << “The number is: “ << num;
return 0;
}
Output:
Enter an integer: 70
The number is: 70
#include <iostream>
using namespace std;
int main()
{
char a;
int num;
cout << "Enter a character and an integer: ";
cin >> a >> num;
cout << "Character: " << a << endl;
cout << "Number: " << num;
return 0;
}
Output:
Enter a character and an integer: F
23
Character: F
Number: 23
15
Example: How gets() and puts() function works
#include <iostream>
using namespace std;
int main()
{
char str[100];
cout << "Enter a string: ";
gets(str);
cout << "You entered: " ;
puts(str);
return 0;
}
Output:
Enter a string: Have a great day!
You entered: Have a great day!
Example: How write() function works
#include <iostream>
using namespace std;
int main()
{
// this function display
// ncount character from array
cout.write("Hello World!", 5);
}
Output:
Hello
Example: Writing to a file
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream of("testout1.txt");
if (of.is_open())
{
of << "Welcome to ";
of << "C++ Tutorial.\n";
of.close();
}
else
cout <<"File opening is fail.";
return 0;
}
16
Example: Reading from a file
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
string srg;
ifstream ifs("testout1.txt");
if (ifs.is_open())
{
while ( getline (ifs,srg) )
{
cout << srg <<endl;
}
ifs.close();
}
else
cout << "File opening is fail."<<endl;
return 0;
}
17
S.No Stream Description
1 cin Standard input stream, usually the keyboard
2 cout Standard input stream, usually the monitor
3 cerr Un-buffered standard error stream, usually the monitor
4 clog Buffered standard error stream, usually the monitor
Cin:
It is used to read input from the standard input device which is usually a keyboard. The
extraction operator (>>) is used along with the object cin for reading inputs.
Cout:
It is used to display the output on a standard output device which is usually the monitor. The
insertion operator (<<) is used along with the object cout for displaying outputs.
Cerr:
The cerr is the standard error stream that is used to output the errors. This is also an instance
of the ostream class. As cerr in C++ is un-buffered so it is used when one needs to display the
error message immediately. It does not have any buffer to store the error message and display
it later.
Clog:
The clog is the Buffered standard error stream. This is also an instance of ostream class and
used to display errors but unlike cerr the error is first inserted into a buffer and then The error
message will be displayed on the screen.
Write an example program to display a message using predefined objects.
#include <iostream>
using namespace std;
int main()
{
int n;
cout <<"Enter an integer: ";
cin>>n;
cout<<"The entered no is:"<<n<<endl;
cout<<"Hello World displayed on monitor"<<endl;
cerr<<"Un-buffered standard error"<<endl;
clog<<"Buffered standard error"<<endl;
return 0;
}
Output:
Enter an integer: 11
The entered no is:11
Hello World displayed on monitor
Un-buffered standard error
Buffered standard error
18
Buffering:
A temporary storage area is called a buffer. All standard input and output devices contain an
input and output buffer. In standard C/C++, streams are buffered.
For example, in the case of standard input, when we press the key on the keyboard, it isn’t
sent to your program, rather it is buffered by the operating system till the time is allotted to that
program.
Example-1:
#include<iostream>
using namespace std;
int main()
{
int a;
char ch[10];
cout<<"Enter an integer:";
cin>>a;
cout<<"Enter any name up to 10 charactes:"<<endl;
cin.getline(ch,10);
cout << a << endl;
cout << ch << endl;
return 0;
}
Output:
Enter an integer:10
Enter any name up to 10 charactes:
10
Example-2: Example-3:
#include<iostream> #include<iostream>
using namespace std; using namespace std;
int main() int main()
{ {
int a; int a;
char ch[10]; char ch[10];
cout<<"Enter an integer:"; cout<<"Enter any string: ";
cin>>a; cin.getline(ch,10);
cin >> ws; cout<<"Enter an integer:";
cin.getline(ch,10); cin>>a;
cout << a << endl; cout << a << endl;
cout << ch << endl; cout << ch << endl;
return 0; return 0;
} }
Output: Output:
Enter an integer:10 Enter any string:Hello
hello Enter an integer:10
10 10
hello Hello
19
Stream Classes:
20
Fig. Working of cin and cout statements
21
22
Type Casting with cout statement:
A type cast is basically a conversion from one type (data type) to another (data type). There
are two types of type conversion:
1. Implicit Type Conversion / Casting
2. Explicit Type Conversion / Casting
Implicit Type Conversion / Casting:
1. It is also called as ‘automatic type conversion’.
2. Done by the compiler on its own, without any external trigger from the user.
Example:
// An example of implicit conversion
#include <iostream>
using namespace std;
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
// y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
float z = x + 1.5;
return 0;
}
Output:
23
x = 107
y=a
z = 108.5
Explicit Type Conversion / Casting:
Examples:
24
Example Programs:
1. Write a c++ program to demonstrate the use of get(), peek() , ignore() and putback()
functions.
#include <iostream>
using namespace std;
int main()
{
char ch;
cout << "Enter a phrase: ";
while ( cin.get(ch) )
{
if (ch == '!')
cin.putback('$');
else
cout << ch;
while (cin.peek() == '#')
cin.ignore(1,'#');
}
return 0;
}
Output:
Now!is#the!time#for!fun#!
Now$isthe$timefor$fun$
25
2. Write a c++ program to demonstrate the use of getline() and gcount() functions.
#include <iostream>
using namespace std;
int main()
{
char name[20];
int len;
cout<<"Enter text:"<<endl;
cin.getline(name,20);
len=cin.gcount();
cout<<"The number of chars is:"<<len<<endl;
return 0;
}
Output:
Enter text:
Welcome to C++
The number of chars is:15
26
Example: Write a program to display the formatted output using IOS Functions and
flags.
#include <iostream>
using namespace std;
int main()
{
cout.width(6); // sets the width with given integer
int x=cout.width(); // returns current width
cout<<"The current width is:"<<x<<endl;
cout.width(20);
cout.setf(ios::left,ios::adjustfield); // sets the justification left
cout<<"C++"<<endl;
return 0;
}
Output:
The current width is:6
A
3.15
************123
C++*****************
1b
27
Example: Write a program to display the formatted output using manipulator.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
// setting the width and precision at a time
cout<<setw(10)<<fixed<<setprecision(2)<<3.14567;
cout<<endl; // splits the new line
cout<<hex<<setiosflags(ios::showbase | ios::uppercase)<<15<<endl;
cout<<"The octal value of 23 is:"<<oct<<23<<endl; // Convert hex into oct
int x;
cout<<"Enter a number:"<<endl;
cin>>hex>>x; // reading a number into hexa decimal format
cout<<hex<<x<<endl;
}
Output:
28
Example:
#include <iostream>
#include <iomanip>
using namespace std;
Output:
1 2 3
Bit Fields:
1. Bit Fields are used to save memory or to restrict memory of members of structure.
2. Using bitfield we can specify the memory to be allocated for individual members of a
structure.
3. When we use structures in the c programming language, the memory required by
structure variable is the sum of memory required by all individual members of that
structure.
To understand the bitfields, let us consider the following example code.
#include <iostream>
using namespace std;
struct Date
{
unsigned int day;
unsigned int month;
unsigned int year;
};
29
int main()
{
cout << sizeof(Date) << endl; // usually prints 12
}
In the above example structure the members day and month both does not requires 2 bytes
of memory for each. Because member day stores values from 1 to 31 only which requires 5
bits of memory, and the member month stores values from 1 to 12 only which required 4 bits
of memory. So, to save the memory we use the bitfields.
#include <iostream>
using namespace std;
struct Date
{
unsigned int day : 5;
unsigned int month : 4;
unsigned int year;
};
int main()
{
cout << sizeof(Date) << endl;
}
30
Example:
Write a C++ program that uses various Flags of ios?
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << hex;
cout << setiosflags (ios::showbase | ios::uppercase);
cout << 100 << endl;
cout << setiosflags(ios::showpos) << setiosflags(ios::scientific) << 123 << 123.23<<endl;
int num = 50;
cout << "Before reset: \n"
<< hex
<< setiosflags(ios::showbase)
<< num << endl;
// Using resetiosflags()
cout << "Resetting showbase flag"
<< " using resetiosflags: \n"
<< resetiosflags(ios::showbase)
<< num << endl;
}
Output:
31
Assignment Questions:
1.a) Briefly write about the evolution of C++.
b) What are the differences between C and C++?
2.a) State the important features/ key concepts/ principles of object-oriented programming. List
the advantages of OOP?
b) List the drawbacks of conventional programming. Explain how object oriented
programming overcome them.
3.a) Present the structure of C++ program. Explain different elements in it. Give example.
b) Discuss about the Bit Fields. Give example
4. a) What is stream and stream classes? How streams are represented in C++?
b) Discuss about the member functions of iostream class.
5. a) Discuss about Formatted and Unformatted data.
b) Explain formatted and unformatted console I/O operations with examples.
32