Oops - UNIT-1
Oops - UNIT-1
UNIT – 1
Introduction to C++: Difference between C and C++, Evolution of C++, The Object Oriented
Technology, Disadvantage of Conventional Programming-, Key Concepts of Object Oriented
Programming, Advantage of OOP, Object Oriented Language.
--------------------------------------------------------------------------------------------------------------------------- ---
1.1 Difference between C and C++
Some difference between C and C++ are as follows:
1) C is a procedure/function-oriented programming language and C++ language is driven by a
procedure/object.
2) Data is not protected in C, whereas data is secured in C++. Data hiding concept is absent in C
3) C uses a top-down approach while C++ uses a bottom-up approach. The program is prepared
by step by step in C, while C++ base elements as prepared first.
4) In C, we can’t give the same name to two functions in a program, whereas due to the function
overloading feature, the above concept is possible in C++. One can initialize a number of
functions with the same name, but with different arguments. The polymorphism feature is built
in C++, which supports this concept.
5) C uses printf() and scanf() functions to write and read the data respectively, while C+++ uses
cout and cin objects for output and input operations, respectively. Further cout uses
<<(insertion operator) and cin uses >>(extraction operator).
6) C uses stdio.h file for input and output functions, whereas C++ uses iostream.h for these
functions.
7) Constructor and destructors are absent in C and the same are provided in C++.
8) Inline functions are supported by C++, and the same are absent in C. Inline functions can be
used as macros. They are stated by a word ‘inline’
9) The C language provides calloc() and malloc() for dynamic allocation of memory and free()
for deallocation of memory. And the C++ language provides a new operator for the allocation
of memory and a delete operator for the deallocation of memory.
10) The C language does not support virtual and friend functions. And the C++ language supports
virtual and friend functions.
11) The namespace feature groups various entities like objects, classes, and functions under a
specific name. No namespace features are present in the C language. The C++ language uses
the namespace features to help avoid name collisions.
12) It does not provide any direct support for exceptional handling. It provides direct support for
exceptional handling. The C++ language uses a try-catch block.
--------------------------------------X--------------------------------------
Page 1
Unit 1- Introduction to C++
C++ is an object oriented programming language and also considered as an extension of C.
Bjarne Stroustrup at AT&T Bell Laboratories in Murray Hill, New Jersey (USA) developed
this language in the year 1980.
He combined the features of both the languages C and SIMULA67 and developed a powerful
language that supports object oriented programming with features of C. The new language is
named as C WITH CLASSES.
Later, various features from ALGOL 68 were added to C WITH CLASSES and the name
changed to C++ in 1983 by Rick Mascitti.
The thought of C++ came from the C increment operator ++. Therefore, C++ is an extension of
C. C++ is a superset of C. All the concepts of C are applicable to C++ also.
--------------------------------------X--------------------------------------
Page 2
Unit 1- Introduction to C++
As shown in the above figure, an institute is divided into different departments such as library,
class room, computer laboratory, etc. each department performs its own activities in
association with the other departments. Each department may be considered as a module and
it contains class and object in C++ language. This theory of class and object can be extended
to every walk of life and can be implemented with software. In general, objects are in terms of
entities. In object oriented programming, objects of a program interact by sending messages to
each other.
--------------------------------------X--------------------------------------
To reduce complexity, functions or modules were introduced which divides a large program
into a set of cohesive units. Each unit is called a function and each function can call other
functions as shown below:
Even though functions reduces complexity, with a lot of functions sharing a common set of global
data may lead to logical errors.
Page 3
Unit 1- Introduction to C++
1. Programs are divided into a set of functions which can share data. Hence, no data security.
2. Focus is on the code to perform the task but not on the data needed.
3. Data is shared globally by several functions which might lead to logical errors.
4. No restrictions on which functions can share the global data.
--------------------------------------X--------------------------------------
The Monolithic programming paradigm is the oldest. It has the following characteristics. It is also
known as the imperative programming paradigm.
This paradigm introduces a modular programming concept where a larger program is divided
into smaller modules.
It provides the concept of code reusability.
It is introduced with the concept of data types.
It also provides flow control statements that provide more control to the user.
In this paradigm, all the data is used as global data which leads to data insecurity.
Page 4
Unit 1- Introduction to C++
The procedure-oriented programming paradigm is the advanced paradigm of a structure-oriented
paradigm. It has the following characteristics.
This paradigm introduces a modular programming concept where a larger program is divided
into smaller modules.
It provides the concept of code reusability.
It is introduced with the concept of data types.
It also provides flow control statements that provide more control to the user.
It follows all the concepts of structure-oriented programming paradigm but the data is defined
as global data, and also local data to the individual modules.
In this paradigm, functions may transform data from one form to another.
The object-oriented programming paradigm is the most popular. It has the following
characteristics.
--------------------------------------X--------------------------------------
Page 5
Unit 1- Introduction to C++
Some of the real world examples for objects are shown below:
Object: City
Data:
Name_of_city
Popukation
Area
Functions:
Average age
Literacy_rate
Display
Representation of an Object
2) Classes
A class is a collection of similar objects that have similar properties and exhibit similar
behavior. A class is a template or blueprint for creating objects. After a class is created, we can
create any number of objects. A class does not occupy any memory like an object.
Real world examples of classes are shown below:
Page 6
Unit 1- Introduction to C++
3) Methods
An operation represents the behavior of an object. When an operation is coded in a class, it is
called a method. All objects in a class perform certain common actions or operations.
Following figure shows a class, its data members, and methods written in different styles:
4) Data Abstraction
Abstraction refers to the process of presenting essential features without including any complex
background details. A class uses this abstraction to represent only essential properties and
behavior.
A powerful way to achieve abstraction is by manipulating hierarchical classifications. This
allows us to divide the system into several logical layers which can be maintained separately.
Real world example for abstraction is a computer which is a single unit made up of several units
(parts) as shown below:
Page 7
Unit 1- Introduction to C++
5) Encapsulation
The packing of data and functions together into a single unit is known as encapsulation.
Encapsulation is implemented by classes. A class contains data which is generally private and is
accessible to the outside world only through public methods.
A side effect of encapsulation is data hiding which allows the users to use an object without
knowing its internal details. Following figure represents different sections of encapsulation :
6) Inheritance
Deriving properties of an object from one class to object of another class is known as
inheritance. Inheritance promotes the feature of object-oriented programming, reusability.
Using inheritance a new class can be created without affecting the existing class. We can use
already available functionality of the existing class and add new functionality in the new class
based on the requirements.
Consider a group of vehicles. We need to create classes for Bus, Car and Truck. The methods
fuelAmount(), capacity(), applyBrakes() will be same for all of the three classes. If we create
these classes avoiding inheritance then we have to write all of these functions in each of the
three classes as shown in below figure:
We can clearly see that above process results in duplication of same code 3 times. This
increases the chances of error and data redundancy. To avoid this type of situation, inheritance
is used. If we create a class Vehicle and write these three functions in it and inherit the rest of
the classes from the vehicle class, then we can simply avoid the duplication of data and increase
re-usability. Look at the below diagram in which the three classes are inherited from vehicle
class:
Page 8
Unit 1- Introduction to C++
Using inheritance, we have to write the functions only one time instead of three times as we
have inherited rest of the three classes from base class(Vehicle).
7) Polymorphism
Single method exhibiting different behaviors in the same class or different classes is known as
polymorphism. We can code a generic interface (set of methods) to a set of associated actions.
As a real world example for polymorphism consider a generic Line class which contains a
method Display(). Now consider three specific classes: DottedObject,
SingleObject, and DashObject which in turn also contains the same Display() method as
shown below:
8) Dynamic Binding
The process of associating an action to a message at run-time is known as dynamic binding
which is also known as late binding. The action to be associated is recognized when the object
is created which is done at run-time.
As an example, consider the above hierarchy in which a Line object can call
the Display() method in any of the three child classes: DottedObject,
SingleObject, or DashObject.
9) Message Passing
Objects communicate through messages. A message is a request for an action. Object sending
the message can also pass data (parameters). Object which receives the message invokes a
corresponding member function (action).
Consider the following example which represents message passing:
Page 9
Unit 1- Introduction to C++
10) Reusability
Using the code available in an existing class to create new classes is known as reusability which
is an important feature of object-orientation. In the below example, class A is an already
existing class from which class B is created and from class B, class C is created:
11) Delegation
In object-oriented programming, two classes can be joined either by inheritance or delegation.
Both of them promote reusability of code.
As shown in the below figure (a), class Y is derived from class X. Here class Y is a kind of X.
This kind of relationship between Y and X classes is known as inheritance. Inheritance is also
known as is a relationship.
Also as shown in figure (b) below, objects of classes A and B are members of class C. This kind
of relationship is known as has a relationship and is also called as delegation or composition.
12) Genericity
The software components (like classes) can have more than one implementation based on the
data type of arguments. Programmer can create a generic class or function which can work with
different types of arguments. The template feature in C++ allows generic programming.
For example, a list data structure can operate on integers, characters, strings, floats or any other
types of objects. So, a programmer can create a generic List class which can accept any kind of
data.
--------------------------------------X--------------------------------------
Page 10
Unit 1- Introduction to C++
1.7 Advantage of OOP
Object-oriented programming offers many advantages to the programmers and users. This technology
allows programmers to create high quality software at an affordable price. Following are the advantages
of OOP:
--------------------------------------X--------------------------------------
Page 11
Unit 1- Introduction to C++
Polymorphism
Binding(Early & Both Both Late Early Both
Late)
Genericity X X X
Class Libraries
Garbage
Collection
Persistence X X X X X
Concurrency Poor Poor X X
The following are the object-oriented languages, which are widely accepted by the programmer.
C++
Smalltalk
Charm ++
Java
--------------------------------------X--------------------------------------
Page 12
Unit 1- Introduction to C++
medium-sized programs. designing large and complex programs.
In POP, Data can move freely from function to In OOP, objects can move and communicate
function in the system with each other through member functions.
To add new data and function in POP is not so OOP provides an easy way to add new data
easy and function.
The main focus is on solving the problem. The main focus is on data security.
It doesn’t support data abstraction. It supports data abstraction using access
specifiers that are public, protected, and
private.
It doesn’t support inheritance. It supports the inheritance of four types.
Overloading is not supported. It supports the overloading of function and
also the operator.
There is no concept of friend function and It has the concept of friend function and
virtual functions. virtual functions.
Examples - C, FORTRAN Examples - C++ , Java , VB.net, C#.net,
Python, R Programming, etc.
-----------------------------X-----------------------
1.10 Advantages and disadvantages of procedural programming
Advantages:
Disadvantages:
C++ program consists of classes, functions, variables, and other statements. The fig. shows four different
parts of a C++ program
Page 13
Unit 1- Introduction to C++
#include<iostream.h>
#define PI 3.14159
int main()
{
int r = 10;
float cir;
cir = PI * (r * r);
cout<<"Area of Circle: "<<cir<<endl;
return 0;
}
Page 14
Unit 1- Introduction to C++
#include directive is used to read the content of file that is included at the beginning of the
program. Another file can be included at the start of the program with
#include name_of_the_file.cpp. The #include directive inserts a copy of the header file directly
into the .cpp file prior to compilation.
Example:
#include<iostream.h> or #include ”iostream”
It contains the contents of iostream header file in the program before compilation. This header
file is required for input output statements such as cin and cout.
It contains the contents of iostream header file in the program before compilation. This header
file is required for input output statements.
b) Class declaration or definition:
Declaration of class is done in this section. In class definition, prototype or definitions of function
are also declared.
c) Class function definitions:
This part contains definitions of functions. The definition of function can also be written outside
the class but before main(). The outside definitions of function should need class name and scope
access operator (::) before the function name.
d) The main() function:
#include <iostream>
using namespace std;
int main()
{
cout<<"Welcome to TutorialRide";
return 0;
}
Output:
Welcome to TutorialRide
/* First C++ /*...*/ comments are used for the documentation to understand the code to others.
Program */ These comments are ignored by the compiler.
#include<iostream> It is a preprocessor directive. It contains the contents of iostream header file in
the program before compilation. This header file is required for input output
statements.
int/void Integer (int) returns a value. In the above program it returns value 0. Void does
not return a value so there is no need to write return keyword.
main() It is an entry point of all the function where program execution begins.
Curly Braces {...} It is used to group all statements together.
std::cout It is requried when we use #include . Std::cout defines that we are using a
name (cout) which belongs to namespace std. Namespace is a new concept
introduced by ANSI where C++ standard libraries are defined.
Page 15
Unit 1- Introduction to C++
If using namespace std is placed into the program then it does not required
to write std:: throughout the code. Namespace std contains all the classes,
objects and functions of the standard C++ library.
"Welcome to The words in inverted commas are called a String. Each letter is called a
TutorialRide" character and series of characters that is grouped together is called a String.
String always be put between inverted commas.
<< It is the insertion stream operator. This operator sends the content of variables
on its right to the object on its left.
STRUCTURE CLASS
Structure is a collection of variables of differentA Class is defined as a collection of related
data types under a single name. variables and functions encapsulated in a single
structure.
Example: Example:
We want to store some information about a Apart from the name, citiNo and salary we have
person: his/her name, citizenship number and relationships such as getdata and putdata to
salary. We can easily create different variables work on variables under single name person
name, citiNo, and salary to store these
information separately under single name
person.
Structure is a value type and its object is crated Class is a reference type and its object is created
on the stack memory on the heap memory
Syntax for structure declaration: Syntax for class declaration:
Example: Example:
struct Person class Person
{ {
char name[50]; char name[50];
Page 16
Unit 1- Introduction to C++
int age; int age;
float salary; float salary;
}; public:
void getdata();
void putdata();
};
Members of a class are public by default. Members of a class are private by default
Declaring the instance of structure: Declaring the instance of class:
int main(){ int main(){
person p1, p2; person p1, p2;
} }
The instances of the structure are called The instances of classes are called “objects”
“structure variable”.
Accessing structure members: Accessing class members:
Through structure variable and dot (.) operator Only public members can be accessed through
object and dot (.) operator
#include <iostream> #include <iostream>
----------------------------------------------------------X-----------------------------------------------------
Applications of OOPS
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
Page 17
Unit 1- Introduction to C++
1.13 Sample CPP Programs
Enter radius 2
Method 2:
//Calculating area of a circle with function
#include<iostream>
using namespace std;
float area(); //function declaration
float area( ) //function definition
{
int r;
float pi, a;
cout<<"\nEnter radius";
cin>>r;
pi = 3.14;
a = pi * r *r;
return a;
}
int main()
{
cout<<"\nArea of a circle = "<<area(); //function call
return 0;
}
Output:
Enter radius 4
Method 3:
Page 18
Unit 1- Introduction to C++
//Calculating area of a circle with member function
#include<iostream>
using namespace std;
class A{
private:
int r;
public:
float area(); //member function declaration
};
float A::area( ) //member function definition
{
float pi, a;
cout<<"\nEnter radius";
cin>>r;
pi = 3.14;
a = pi * r *r;
return a;
}
int main()
{
A obj;
cout<<"\nArea of a circle = "<<obj.area(); //member function call
return 0;
}
Output:
Enter radius 3
Before swapping….
a = 12 b = 34
After sapping….
a = 34 b = 12
Write a C++ program to swap two numbers without using temporary variable.
//swapping two variables using + and -
#include<iostream>
using namespace std;
int main()
{
int a, b;
cout<<"\nEnter two integer values: ";
cin>>a>>b;
cout<<"\n Before swapping….\n";
cout<<"\na = "<<a<<"\tb = "<<b<<endl;
Page 20
Unit 1- Introduction to C++
a = a+b;
b = a-b;
a = a-b;
cout<<"\nAfter sapping….\n";
cout<<"\na = "<<a<<"\tb = "<<b<<endl;
return 0;
}
Output:
Before swapping….
a = 23 b = 45
After sapping….
a = 45 b = 23
int main()
{
int i;
char c;
float f;
double d;
return 0;
}
Output:
Size of int is: 4
Size of char is: 1
Page 21
Unit 1- Introduction to C++
Size of float is: 4
Size of double is: 8
int main()
{
int n;
if ( n % 2 == 0)
cout << n << " is even.";
else
cout << n << " is odd.";
return 0;
}
Output:
Enter an integer: 23
23 is odd.
Write a C++ program to Check Whether Number is Even or Odd using ternary operators
//Check Whether Number is Even or Odd using ternary operators
#include <iostream>
using namespace std;
int main()
{
int n;
(n % 2 == 0) ? cout << n << " is even." : cout << n << " is odd.";
return 0;
}
Output:
Enter an integer: 48
48 is even.
Page 22
Unit 1- Introduction to C++
Write a C++ Program to find Factorial Program using Loop
//c++ program to find factorial of a given number
#include <iostream>
using namespace std;
int main()
{
int i,fact=1,number;
cout<<"Enter any Number: ";
cin>>number;
for(i=1;i<=number;i++){
fact=fact*i;
}
cout<<"Factorial of " <<number<<" is: "<<fact<<endl;
return 0;
}
Output:
Enter any Number: 5
Factorial of 5 is: 120
Write a program in C++ to find the factorial of a given number using recursion.
// Factorial of a given number using recursion
#include<iostream>
using namespace std;
int main()
{
int factorial(int);
int fact,value;
cout<<"Enter any number: ";
cin>>value;
fact=factorial(value);
cout<<"Factorial of a number is: "<<fact<<endl;
return 0;
}
int factorial(int n)
{
if(n<0)
return(-1); /*Wrong value*/
if(n==0)
return(1); /*Terminating condition*/
else
{
return(n*factorial(n-1));
}
}
Output:
Enter any number: 6
Factorial of a number is: 720
Page 23
Unit 1- Introduction to C++
Sample Questions:
Page 24