0% found this document useful (0 votes)
17 views44 pages

Oop 1

Uploaded by

hassan313.g4l
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views44 pages

Oop 1

Uploaded by

hassan313.g4l
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

1 ‫البرمجه الشيئيه‬ ‫الكورس األول‬-‫المحبضره االولى‬

Overview for functions


A function is a set of statements designed to accomplish a particular task.
The advantage of using functions is that it is possible to reduce the size of a
program by calling and using them at different places in the program. C++
has added many new features to functions to make them more reliable and
flexible.
General Format of a Function Definition:
Functions can be define before the definition of the main() function, or they
can be declared before it and define after it.
Declaring a function means listing its return type, name, and arguments.
This line is called the function prototype. A function prototype tells the
compiler the type of data returned by the function. It is usually defined after
the preprocessing statements at the beginning of the program.

Figure 1: Function syntax.:


2 ‫البرمجه الشيئيه‬ ‫الكورس األول‬-‫المحبضره االولى‬

Example 1: Write a C++ program to find the maximum value between two values
using function
#include <iostream.h>
float max ()
{
float a, b; a=3.5; b=10.25;
float c;
if (a > b)
c = a;
else
c = b;
return (c);
}
void main ( )
{ float k;
Output:-
k=max();
cout <<k; 10.25
}

Local and Global Variables:

#include <iostream.h>
void sum ()
{ int a,b,s; // a,b,s are local variables in a function sum()
a=3;
b=5;
s=a+b;
cout<<s;
}
void main( )
{
sum();
}
3 ‫البرمجه الشيئيه‬ ‫الكورس األول‬-‫المحبضره االولى‬

#include <iostream.h>
int a,b,s; // a,b,s are Global variables
void sum ()
{ s=a+b;
cout<<s;
}
void main( )
{ a=3;
b=5;
sum();
}

Inline Function:
C++ suppliers’ programmers with the inline keyword, which can speed up
programs by making very short functions execute more efficiently. Normally
a function resides in a separate part of memory, and is referred to by a
running program in which it is called. Inline functions save the step of
retrieving the function during execution time, at the cost of a larger compiled
program.
4 ‫البرمجه الشيئيه‬ ‫الكورس األول‬-‫المحبضره االولى‬

Figure: Functions versus inline code

Example 2: Write a C++ program to find the square of a number using inline
function

#include<iostream.h>
inline int square ( int y )
{
return ( y*y );
}
void main( )
{
int m;
m=5;
cout<< square ( m ) ;
}
5 ‫البرمجه الشيئيه‬ ‫الكورس األول‬-‫المحبضره االولى‬

Function Overloading:
Overloading refers to the use the same thing for different purposes. C++ also
permits overloading of functions. This means that we can use the same
function name to create functions that perform a variety of different tasks.
We can design a family of functions with one function name but with
different argument lists. The function would perform different operations
depending on the argument list in the function call.

Example3:

e4:
6 ‫البرمجه الشيئيه‬ ‫الكورس األول‬-‫المحبضره االولى‬

Passing Parameters:
There are two main methods for passing parameters to a program:
1- Passing by Value:
When parameters are passed by value, a copy of the parameters value is taken
from the calling function and passed to the called function. The original variables
inside the calling function, regardless of changes made by the function to it are
parameters will not change. All the pervious examples used this method.
Example 4
 Write C++ program using function to calculate the average of
two numbers entered by the user in the main program:
#include<iostream.h>

void aver (int x1, int x2)


{
float z;
z = ( x1 + x2) / 2.0; Output:-
cout<<z; 4.5
}
void main( )
{
int num1,num2; Input:-
cout << "Enter 2 numbers \n"; Enter 2 numbers
cin >> num1 >> num2;
6 3
aver (num1, num2);

2- Passing by Reference:
When parameters are passed by reference their addresses are copied to the
corresponding arguments in the called function, instead of copying their values.
Thus pointers are usually used in function arguments list to receive passed
references.
‫‪7‬‬ ‫البرمجه الشيئيه‬ ‫المحبضره االولى‪-‬الكورس األول‬

‫‪Example 5:‬‬

‫‪E‬‬
8 ‫البرمجه الشيئيه‬ ‫الكورس األول‬-‫المحبضره االولى‬

Example 7:

Default Arguments
As with global functions, a member function of a class may have default
arguments. The same rules apply: all default arguments should be trailing
arguments, and the argument should be an expression consisting of objects
defined within the scope in which the class appears.
Surprisingly, a function can be called without specifying all its arguments.
This won’t work on just any function: The function declaration must provide
default values for those arguments that are not specified.
9 ‫البرمجه الشيئيه‬ ‫الكورس األول‬-‫المحبضره االولى‬

Example 8:Write a simple program to represent a default argument

In this program the function repchar() takes two arguments. The first time it’s
called with no arguments, the second time with one, and the third time with two.
Why do the first two calls work? Because the called function provides default
arguments, which will be used if the calling program doesn’t supply them. The
default arguments are specified in the declaration for repchar(): void
repchar(char=’*’, int=45); The default argument follows an equal sign, which is
placed directly after the type name. You can also use variable names, as in void
repchar(char reptChar=’*’, int numberReps=45); If one argument is missing
when the function is called, it is assumed to be the last argument. The repchar()
function assigns the value of the single argument to the ch parameter and uses the
default value 45 for the n parameter. If both arguments are missing, the function
assigns the default value ‘*’ to ch and the default value 45 to n.
1 )1( ‫البرمجه الشيئيه‬ ‫الكورس األول‬-‫المحبضره الثبنيه‬

Overview of OOP:
When working with computers, it is very important to be fashionable. In the
1960s, the new fashion was what was called high-level languages (H.L.L.)
such as FORTRAN and COBOL, in which the programmer did not have to
understand the machine instructions.
In the 1970s, people realized that there were better ways to program than
with a jumble of GOTO statements, and the structured programming
languages such as PASCAL were invented.
In the 1980s, much time was invested in trying to get good results out of
fourth-generation languages (4GLs), in which complicated programming
structures could be coded in a few words. There were also schemes such as
Analyst Workbenches, which made systems analysts into highly paid and
overqualified programmers.

Bjarne Stroustrup at Bell Labs developed C++ during 198-1985. The term
C++ was first used in 1983. Prior to 1983, Stroustrup added features to C
programming language and formed what he called “C with Classes”. In
addition to the efficiency and portability of C, C++ provides number of new
features. C++ programming language is basically an extension of C
programming language.
The fashion of the 1990s is most definitely object-oriented programming.
Read any book on object-oriented programming, and the first things you will
read about are three importance OOP features:
• Encapsulation and Data Hiding.
• Inheritance and Reuse.
• Polymorphism.
2 )1( ‫البرمجه الشيئيه‬ ‫الكورس األول‬-‫المحبضره الثبنيه‬

Figure 1: The three pillars of OOP.

Encapsulation and Data Hiding:


C++ supports the properties of encapsulation and data hiding through the
creation of user-defined types, called classes.
Once created, class acts as a fully encapsulated entity, it is used as a whole
unit. The actual inner workings of the class should be hidden. Users of a
well-defined class do not need to know how the class works; they just need
to know how to use it.
Inheritance and Reuse:
C++ supports the idea of reuse through inheritance. A new type, which is
an extension of an existing type, can be declared. This new subclass is said
to derive from the existing type and is sometimes called a derived type. The
Quasar model is derived from the Star model and thus inherits all its
qualities, but can add to them as needed.
Polymorphism:
C++ supports the idea that different objects do "the right thing" through
what is called function polymorphism and class polymorphism.
3 )1( ‫البرمجه الشيئيه‬ ‫الكورس األول‬-‫المحبضره الثبنيه‬

Poly means many, and morph means form. Polymorphism refers to the same
name taking many forms.
Class Definition:
Class is a keyword, whose functionality is similar to that of the struct
keyword, but with the possibility of including functions as members, instead
of only data.
Classes are collections of variables and functions that operate on those
variables. The variables in a class definition are called data members, and
the functions are called member functions.

Note: Class is a specification for number of objects.

A class definition consists of two parts: header and body. The class header
specifies the class name and its base classes. The class body defines the
class members. Two types of members are supported:
 Data members have the syntax of variable definitions and specify the
representation of class objects.
 Member functions have the syntax of function prototypes and
specify the class operations, also called the class interface.
4 )1( ‫البرمجه الشيئيه‬ ‫الكورس األول‬-‫المحبضره الثبنيه‬

Class members fall under one of three different access permission


categories:
 Public members are accessible by all class users.
 Private members are only accessible by the class members.
 ·Protected members are only accessible by the class members and the
members of a derived class.

Figure 2: Public and Private Definition


5 )1( ‫البرمجه الشيئيه‬ ‫الكورس األول‬-‫المحبضره الثبنيه‬

Example 1: write an OOP to find the area of rectangle using a class called
rectangle

Output
42
6 )1( ‫البرمجه الشيئيه‬ ‫الكورس األول‬-‫المحبضره الثبنيه‬

Example 2: write an OOP to read a data and print it. Create a class
called data with one data member called (a).

Output:
Data is 1066
Data is 1776
7 )1( ‫البرمجه الشيئيه‬ ‫الكورس األول‬-‫المحبضره الثبنيه‬

Example 3: write an OOP to define the coordinate of point and shift


these values of this point.

Output
1222
1 )1(‫البرمجه الشيئيه‬ ‫الكورس األول‬-‫المحبضره الثبلثه‬

Class Constructors and Destructors:


A class constructor is a function that is executed automatically whenever a
new instance of a given class is declared.
The main purpose of a class constructor is to perform any initializations
related to the class instances via passing of some parameter values as initial
values and allocate proper memory locations for that object.
Note1: A class constructor must have the same name as that of the
associated class.
Note2: A class constructor has not return type, not even void.
Note3: A class constructor can be overloaded.
Example 1: Write an OOP to represent simple constructor with class
point which contains two data members vxal and yval.

Output
1222
2 )1(‫البرمجه الشيئيه‬ ‫الكورس األول‬-‫المحبضره الثبلثه‬

Example 2: Write an OOP to represent a rectangle constructor.

Output
42

A class may have more than one constructor. To avoid ambiguity, however,
each of these must have a unique signature.
3 )1(‫البرمجه الشيئيه‬ ‫الكورس األول‬-‫المحبضره الثبلثه‬

Example 3: Write an OOP to represent multiple constructors in class


rectangle.

Output
42
63
4 )1(‫البرمجه الشيئيه‬ ‫الكورس األول‬-‫المحبضره الثبلثه‬

Destructor
Just as a constructor is used to initialize an object when it is created, a destructor is
used to clean up the object just before it is destroyed. A destructor always has the
same name as the class itself, but is preceded with a ~ symbol. Unlike
constructors, a class may have at most one destructor. A destructor never takes any
arguments and has no explicit return type.Destructors are generally useful for
classes which have pointer data members which point to memory blocks allocated
by the class itself. In such cases it is important to release member-allocated
memory before the object is destroyed. A destructor can do just that.
Example 1: Write an OOP to represent a simple destructor with class rectangle.

Output
42
5 )1(‫البرمجه الشيئيه‬ ‫الكورس األول‬-‫المحبضره الثبلثه‬

Example2: Write an OOP to represent destructor of pointer members in class


rectangle.

Output
42

Note: A class destructor proceeded with a tilde (~).


1 )1( ‫البرمجه الشيئيه‬ ‫المحبضره الرابعه –الكورس األول‬

Friend function
Occasionally we may need to grant a function access to the nonpublic members of
a class. Such an access is obtained by declaring the function a friend of the class.
There are two possible reasons for requiring this access:
• It may be the only correct way of defining the function.
• It may be necessary if the function is to be implemented efficiently.
Example1: Write an OOP to find the summation of point coordinates using friend
function.

Output:
xval=4 yval=5
the summation of coordinate x & y =9
2 )1( ‫البرمجه الشيئيه‬ ‫المحبضره الرابعه –الكورس األول‬

Example2: Write an OOP to print the square value of the data in class alpha
using friend function .

Output:
81
3 )1( ‫البرمجه الشيئيه‬ ‫المحبضره الرابعه –الكورس األول‬

Example 3: Write an OOP to print the coordinates of a class point and a class
D3 using friend function.

Output:
xval=6
yval=3
zval=5
4 )1( ‫البرمجه الشيئيه‬ ‫المحبضره الرابعه –الكورس األول‬

friend class
The member functions of a class can all be made friends at the same time
when you make the entire class a friend.
Example 1:Write an OOP to divide the value m in a class first on the value n in the
class second using a friend class.

Output:
division=2
5 )1( ‫البرمجه الشيئيه‬ ‫المحبضره الرابعه –الكورس األول‬

Example 2:Write an OOP to read the values x and y in a class read and write the
values x and y in a class write using friend class
1 )1(‫البرمجه الشيئيه‬ ‫المحبضره الخبمسه –الكورس األول‬

Scope Operator
When calling a member function, we usually use an abbreviated syntax. For
example: pt.OffsetPt(2,2); // abbreviated form
This is equivalent to the full form: pt.Point::OffsetPt(2,2); // full form

(
2 )1(‫البرمجه الشيئيه‬ ‫المحبضره الخبمسه –الكورس األول‬

Member Initialization List


There are two ways of initializing the data members of a class.
1) The first approach involves initializing the data members using
assignments in the body of a constructor. For example:

Example 1: Write an OOP to initialize the data member of a class using


assignments in the body of constructor.

Output
15

(
3 )1(‫البرمجه الشيئيه‬ ‫المحبضره الخبمسه –الكورس األول‬

2) The second approach uses a member initialization list in the definition


of a constructor. For example:

Example 2: Write an OOP to initialize the data member of a class in the


definition of constructor.

Output
15

(
4 )1(‫البرمجه الشيئيه‬ ‫المحبضره الخبمسه –الكورس األول‬

Constant member
A class data member may define as constant.
Constant Function Argument
Suppose you want to pass an argument by reference for efficiency, but not
only do you want the function not to modify it, you want a guarantee that the
function cannot modify it. To obtain such a guarantee, you can apply the
const modifier to the variable in the function declaration.
Example 1:Write a C++ simple program to represent a constant argument

Here we want to be sure that aFunc() can’t modify the variable beta. (We
don’t care if it modifies alpha.) So we use the const modifier with beta in the
function declaration (and definition):
void aFunc(int& alpha, const int& beta);

(
5 )1(‫البرمجه الشيئيه‬ ‫المحبضره الخبمسه –الكورس األول‬

Constant Member Functions


We can apply const to variables of basic types such as int to keep them from
being modified. In a similar way, we can apply const to objects of classes.
When an object is declared as const, you can’t modify it.

Example 2:Write an OOP to represent a constant member function

(
6 )1(‫البرمجه الشيئيه‬ ‫المحبضره الخبمسه –الكورس األول‬

Static Members
A data member of a class can be defined to be static. This ensures that there
will be exactly one copy of the member, shared by all objects of the class.

Example 1: Write an OOP to represent a static members for count class.

Output:
c1=1
c2=1
c1=2
c2=1
c1=3
c2=1

(
7 )1(‫البرمجه الشيئيه‬ ‫المحبضره الخبمسه –الكورس األول‬

Example 2: Write an OOP to represent a static members for point class.

Output:
x-coordinate= 1
y-coordinate= 1
x-coordinate= 2
y-coordinate=2

(
1 )1(‫البرمجه الشيئيه‬ ‫المحبضره السبدسه –الكورس األول‬

Objects Pointers
It has already been stated that a pointer is a variable which holds the memory
address of another variable of any basic data type. It has been shown that how a
pointer variable can be declared with a class.
First way :- (*object name).member name=variable;

Example 1: Write an OOP to read and display student information using pointer.
2 )1(‫البرمجه الشيئيه‬ ‫المحبضره السبدسه –الكورس األول‬

Second way:- object name ->member name=variable;

Example 2: Write an OOP to read and display student information using pointer.
3 )1(‫البرمجه الشيئيه‬ ‫المحبضره السبدسه –الكورس األول‬

This pointer
This pointer is a variable which is used to access the address of the class itself.
Example 1:Write an OOP to display the address of class using this pointer

The above program create three objects,obj1, obj2, obj3 and displays each
object’s address using this pointer.
Example 2:Write an OOP to display the content of class member using this pointer
4 )1(‫البرمجه الشيئيه‬ ‫المحبضره السبدسه –الكورس األول‬

References Members
A class data member may define as reference. For example:
Example 1:Write an OOP to find the value of third coordinate z using reference
member.

Output:
z-coordinate= 5
5 )1(‫البرمجه الشيئيه‬ ‫المحبضره السبدسه –الكورس األول‬

Class Object Member


A data member of a class may be of a user-defined type, that is, an object of
another class.
Example 1:Write an OOP to find the area of square using class object member

Output:
area of square= 49
6 )1(‫البرمجه الشيئيه‬ ‫المحبضره السبدسه –الكورس األول‬

Example 2: Write an OOP to find the summation of point coordinates using class
object member

Output:
8
1 )1( ‫البرمجه الشيئيه‬ ‫المحبضره السببعه –الكورس األول‬

Arrays as Class Data Member


In C++, the definition of an array specifies a variable type and a name. But it
includes another feature: a size. The size specifies how many data items the
array will contain.
The items in an array are called elements .All elements in an array are of the
same type; only the values vary. As specified in the definition, the array has
exactly four elements. The first array element is numbered 0. Thus, since
there are four elements, the last one is number 3.

Example 1: Write an OOP to subtract a value 3 from data member with 5 elements.

Output:
4 0 -1 7 -2
2 )1( ‫البرمجه الشيئيه‬ ‫المحبضره السببعه –الكورس األول‬

Object Arrays
 An array of a user-defined type is defined and used much in the same
way as an array of a built-in type.

Example 1: Write an OOP to represent object array of class point for 2 points
objects .

Output:
18 12
7 10
3 )1( ‫البرمجه الشيئيه‬ ‫المحبضره السببعه –الكورس األول‬

Example 2: Write an OOP to read and write student information for 10 students
objects.
4 )1( ‫البرمجه الشيئيه‬ ‫المحبضره السببعه –الكورس األول‬

An Array of Pointers to Objects


A common programming construction is an array of pointers to objects. This
arrangement allows easy access to a group of objects, and is more flexible
than placing the objects themselves in an array.

Example 1: Write an OOP to represent array of pointer to object for class


point with 2 points objects .

Output:
18 12
7 10
5 )1( ‫البرمجه الشيئيه‬ ‫المحبضره السببعه –الكورس األول‬

Example 2: Write an OOP to read and write student information for 10 students
using array of pointer to objects.

You might also like