cpp_unit_1
cpp_unit_1
• 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.
•Stroustrup and a strong supporter of C, wanted to combine of both the languages and create
a more powerful language that could support object-oriented programming features and still
retain the power and elegance of C.
•The result was C++. Therefore, C++ an extension of C with a major addition of the class,
constructs features. The idea of C++ comes from the C increment operator ++, thereby
suggesting that C++ is an incremented version of C.
Why object-oriented programming
•C++ is a superset of C. The most Simple Program
important facilities that C++ adds on
to C are classes, inheritance, #include<iostream.h>
function overloading, and operator #include<conio.h>
overloading.
void main()
•These features enable creating of {
abstract data types inherit properties int a, b, c;
from existing data types and support clrscr();
polymorphism, thereby making C++ a cout<< “enter the value a and b”;
truly object-oriented language. cin >> a>>b;
c=a+b;
cout<<”sum is: ”<< c;
getch();
}
Why object-oriented programming
•The object-oriented features in C++ allow programmers to build large programs with
clarity, extensibility and ease of maintenance, the spirit and efficiency of C.
•Program Explanation
•Comments - C++ introduces a new comment symbol // (double slash). The double slash
comment is basically a single line comment.
•This statement introduces two new C++ features cout and <<.
•The iostream File - We have used the following #include directive in the program
#include<iostream.h>.
•This will bring all the identifiers defined in std to the current global scope. using and
namespace are the new keywords of C++.
Why object-oriented programming
•Return Type of main( ) - In C++ main() returns an integer type value to the operating
system.
•Variable – Variable are those whose value is not fix. The program uses any number of
variables. They can be declared as type of data type by the statement. All variables must be
declared before they are used in the program.
•Input Operator - The statement cin>> number; is an input statement and causes the
program to wait for the user to type in a number.
cin >> a;
Why object-oriented programming
•Cascading of I/O Operators - The multiple
use of << or >> in one statement is called
cascading.
cout<<”Sum = ”<<sum<<”\n”;
cin>>a>>b”\n”;
• The class person includes two basic data type items and
two functions to operate on that data.
•The class declarations are placed in a header file and the definitions of member functions go
into another file. This approach enables the programmer to separate the abstract
specification of the interface (class definition) from the implementation details (member
functions definition).
•Finally, the main program that uses the class is placed in a third file which “include” the
previous two files as well as any other files required.
•This approach is based on the concept of client-server model as shown in previous Fig. The
class definition including the member functions constitute the server that provides services to
the main program known as client, The client uses the server through the public interface of the
class.
Why object-oriented programming
•Procedure oriented programming •Object oriented programming (OOP)
1. Objects 5. Inheritance
2. Classes 6. Polymorphism
3. Data abstraction 7. Dynamic binding
4. Data encapsulation 8. Message passing
•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 or any item that the program
has to handle.
• They may also represent user-defined data such as vectors, time and lists. Programming
problem is analyzed in terms of objects and the nature of communication between
them.
Basic concept of OOPs
• Program objects should be chosen such that they match closely
with the real-world objects. When a program is executed, the
objects interact by sending messages to one another.
• Each object contains data, and code to manipulate the data.
Objects can interact without having to know details of each
other's data or code. It is sufficient to know the type of message
accepted, and the type of response returned by the objects.
• Classes are user-defined data types and behave like the built-in types of programming
language. fruit mango; will create an object mango belonging to the class fruit.
•Data Encapsulation –
• The wrapping up of data and functions into a single unit (called class} is known as
encapsulation. Data encapsulation is the most striking feature of a class.
Basic concept of OOPs
• The data is not accessible to the outside world, and only those functions which are
wrapped in the class can access it. These functions provide the interface between the
data and the program.
• This insulation of' the data from direct access by the program is called data hiding or
information hiding.
•Data Abstraction –
• Abstraction refers to the act of representing essential features without including the
background details or explanations.
• Classes use the concept of abstraction and are defined a list of abstract attributes Such as
Size, weight and cost, and functions to operate on these attributes.
• They encapsulate all the essential properties of the objects that are to be created. The
attributes are sometimes called data members because they hold information. The
functions that operate on these data are sometimes called method is or member
functions.
Basic concept of OOPs
• Since the Classes use the concept of data abstraction, they are known as Abstract Data
Types.
•Inheritance –
• Inheritance is the process by which objects of acquire the properties of objects of
another.
• In OOPs, the concept of inheritance provides the idea of reusability. This means that
we can add additional features to an existing class without modifying it.
• This is possible by deriving a new class from the existing one. The new class will have
the combined features of both the classes.
• The real appeal and power of the inheritance mechanism is that it allows the
programmer to reuse a class that is almost, but not exactly, what he wants, and to tailor
the class in such a way that it does not introduce any undesirable Side-effects into the rest
of the classes.
Basic concept of OOPs
• For example, the bird 'robin' is a part of the class 'flying bird' which is again a part of the
class "bird'. The principle behind this sort of division is that each derived Class shares
characteristics with the class from which it is derived as illustrated in Fig.
Basic concept of OOPs
•Polymorphism –
• Polymorphism is another important OOP concept. Polymorphism, a Greek term, means
the ability to take more than one form.
• An operation may exhibit different behaviours in different instances. The behaviour
depends upon the types of data used in the operation.
• For example, consider the operation of addition. For two numbers, the operation will
generate a sum. If the operands are strings, then the operation would produce a third string
by concatenation. The process of making an operator to exhibit different behaviours in
different instances is known as operator overloading.
• A single function name can be used to handle different number and different types of
arguments. This is something similar to a particular word having several different
meanings depending on the context. Using a single function name to perform d types of
tasks is known function overloading.
Basic concept of OOPs
• 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.
•Dynamic Binding –
• Binding refers to the linking of a procedure call to the code to be executed in response to
the call, Dynamic binding (also known as late binding) means that the associated with a
given procedure call is not known until the time of the call at run-time.
Basic concept of OOPs
• It is associated with polymorphism and inheritance. A function associated with a
polymorphic reference depends on the dynamic type of that reference.
• Consider the procedure "draw" in above Fig. By inheritance, every object will have this
algorithm is, however, unique to each object and so the draw procedure will be redefined
in each class that defines the object. At run-time the code matching the object under
current reference will be called.
•Message Passing –
• An object-oriented program consists of a set of objects that communicate with each other.
The process of programming in an object-oriented language, therefore, involves the
following basic steps:
• Objects communicate with one another by sending and receiving information much the
same way as people pass messages to one another. The concept of message passing makes
it easier to talk about building systems that directly model or simulate their real-world
counterparts.
• A message for an object is a request for execution of a procedure, and therefore will
invoke a function (procedure} in the receiving object that generates the desired result.
• Message passing involves the name of the object, the name of the function (message)
and the information to be sent. Objects have a life cycle. They can be created and
destroyed. Communication with an object is feasible as long as it is alive. Example:
1. Declaration: A function declaration tells the compiler about the number, data types of
parameters, and returns type of function. Writing parameter names in the function
declaration is optional but it is necessary to put them in the definition.
2. Definition: A function definition talks about the body of the function (code to be
executed)
Syntax
void myFunction() // declaration
{
// the body of the function (definition)
}
Inline function
•Types of Functions
1. User Defined Function - Defined by user/customer.-Defined blocks of code specially
customized to reduce the complexity of big programs. They are also commonly known
as “tailor-made functions” .
2. Library or Pre-defined Function - Library functions are also called “built-in
Functions“. These functions are part of a compiler package that is already defined and
consists of a special function with special and different meanings. Built-in Function
gives us an edge as we can directly use them without defining them whereas in the
user-defined function we have to declare and define a function before using them. For
Example: sqrt(), setw(), strcat(), etc.
•Inline function –
• One of the objectives of using functions in a program is to save some memory space,
which becomes appreciable when a function is likely to be called many times.
Inline function
• However, every time a function is called, it takes lot of extra time in executing a of
instructions.
• When a function is small, n substantial percentage of execution time may be spent in
overheads.
• One solution to this problem is to use macro definitions, popularly known as macros.
Preprocessor macros are popular in C.
• The major drawback with macros is that they are not really functions and therefore the
usual error checking does not occur during compilation. #define abc 23
• C++ has a different solution to this problem. To eliminate the cost of calls to small
functions, C++ proposes a new feature called inline function.
• An inline function is a function that is expanded in line when it is invoked, That is, the
compiler replaces the function call with the corresponding function code (something
similar to macros expansion).
• The inline functions defined as follows:
Inline function
Syntax
inline function-header
{ function body }
Example
inline double_cube(double a)
{ return (a*a*a); }
•Some of the situations where inline expansion may not work are:
int main( )
{
clrscr();
float a=2.5;
float b=3.5;
cout<<"Multiplication is :"<<mul(a, b);
return 0;
}
Default argument function
▪ When we define function and at the time of function declaration, the variable declare in
function brackets are known as parameter.
▪ A default argument is a value provided in a function declaration that is automatically
assigned by the compiler. If the calling function doesn’t provide a value for the argument.
In case any value is passed, the default value is overridden.
1. The values passed in the default arguments are not constant. These values can be
overwritten if the value is passed to the function. If not, the previously declared value
retains.
2. During the calling of function, the values are copied from left to right.
3. All the values that will be given default value will be on the right.
▪ The following is a simple C++ example to demonstrate the use of default arguments.
Default argument function
Example
#include <iostream.h>
#include <conio.h>
void main()
{
cout << sum(10, 15) << endl; // Statement 1
cout << sum(10, 15, 25) << endl; // Statement 2
cout << sum(10, 15, 25, 30) << endl; // Statement 3
}
Reference: Independent reference
•C++ supports two types of variables:
•Reference
• Reference is a variable that behaves as an alias for another variable. Reference can be
created by simply using an ampersand (&) operator.
• When we create a variable, then it occupies some memory location. We can create a
reference of the variable; therefore, we can access the original variable by using either
name of the variable or reference.
Reference: Independent reference
• For example, int a=10;
• Now, we create the reference variable of the above variable. int &ref=a;
2. References to non-const values - It can be declared by using & operator with the
reference type variable.
Example
#include <iostream.h>
int main()
{
int a=10;
int &value=a;
Reference: Independent reference
cout << value << endl;
return 0;
}
2.References as aliases - References as aliases is another name of the variable which is being
referenced.
For example,
#include <iostream.h>
int main()
{ a=10 -110111
int a=10; // variable initialization &b=a 110111
int &b=a; b=a 10
int &c=a;
cout << "Value of a is :" <<a<<endl;
cout << "Value of b is :" <<b<<endl;
cout << "Value of c is :" <<c<< endl;
Reference: Independent reference
return 0;
}
int a = 5; int a = 5;
int b = 6; int b = 6;
int *p;
int &p = a; *p = &a;
Int &p = b; *p = &b;
4. Memory Address - In the case of reference, both the reference and actual variable
refer to the same address. The new variable will not be assigned to the reference
variable until the actual variable is either deleted or goes out of the scope.
int a = 5;
int b = 6;
int &p = a;
Reference: Independent reference
int &p = b; // Throw an error of "multiple declaration of reference"
int &q = b; // However it is valid statement,
int *p
&p = a; // pointer address
cout << &p << endl << &a;
5. NULL value - We cannot assign the NULL value to the reference variable, but the
pointer variable can be assigned with a NULL value.
6. Indirection – Pointers can have pointer to pointer offering more than one level of
indirection but reference of reference is not allowed
int a = 10;
int *p;
int **q; // It is valid.
p = &a;
Reference: Independent reference
q = &p;
int &p = a;
int &&q = p; // It is reference to reference, so it is an error
1. Pass by Value: In this parameter passing method, values of actual parameters are
copied to the function’s formal parameters. The actual and formal parameters are stored in
different memory locations so any changes made in the functions are not reflected in the
actual parameters of the caller.
#include <iostream>
2. Pass by Reference: Both actual and formal parameters refer to the same locations, so
any changes made inside the function are reflected in the actual parameters of the caller.
Example
#include <iostream.h>
2. Functions Using Pointers - The third way to use functions with pointer.
Pass by reference
• The function fun() expects a pointer ptr to an integer (or an address of an integer). It
modifies the value at the address ptr. The dereference operator * is used to access the
value at an address.
• In the statement ‘*ptr = 30’, the value at address ptr is changed to 30. The address
operator & is used to get the address of a variable of any data type. In the function
call statement ‘fun(&x)’, the address of x is passed so that x can be modified using its
address.
#include <iostream>