0% found this document useful (0 votes)
48 views

OOSP - Basics

The document provides an overview of object oriented programming concepts in C++ including: 1) It discusses preprocessing directives like #include that allow inclusion of header files like iostream.h containing declarations for cout and cin. 2) It explains output and input streams like cout and cin for displaying output and taking user input, and operators like << and >> for output and input. 3) It demonstrates basic input/output examples using cout, cin, and cascading of operators. 4) It covers flexibility in variable declarations, function prototypes for type checking arguments, function overloading based on argument types, and use of references as aliases to variables.

Uploaded by

Prachi Tiwari
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)
48 views

OOSP - Basics

The document provides an overview of object oriented programming concepts in C++ including: 1) It discusses preprocessing directives like #include that allow inclusion of header files like iostream.h containing declarations for cout and cin. 2) It explains output and input streams like cout and cin for displaying output and taking user input, and operators like << and >> for output and input. 3) It demonstrates basic input/output examples using cout, cin, and cascading of operators. 4) It covers flexibility in variable declarations, function prototypes for type checking arguments, function overloading based on argument types, and use of references as aliases to variables.

Uploaded by

Prachi Tiwari
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/ 31

Object Oriented Programming

Using C++

By
Hemraj Saini
Associate Professor
Department of Computer Science and
Engineering
Preprocessor Directive
• The first line of the program

# include<iostream.h>

tells the compiler to add the source file iostream.h to the


program’s source file.

• It contains the declarations that are needed by the cout, cin


identifiers and the << , >> operators.

• It might look like a program statement but is not a program


statement.

• Instead it starts with a sign (#) called preprocess or


directive.
Output using cout
The identifier cout (pronounced as “Console out”) is actually an
object. It is predefined in C++ to correspond to the standard
output stream. (A stream is an abstraction that refers to a flow
of data).

The standard output stream normally flows to the screen


display – although it can be redirected to other output devices.

The operator << is called the insertion or put to operator. It


directs the contents of the variable on its right to the object on
its left.

Consider the following statement:

cout << “ Welcome to the world of C++” ;

This statement directs the string constant “Welcome to the


world of C++” to cout, which sends it to the display unit.
Input using cin
• The identifier cin (pronounced “console in” ) is an object,
predefined in C++ to correspond to the standard input stream.

• This stream represents the data coming from the keyboard.

• The >> is the extraction or get from operator. It takes value


from the stream object on its left and places it in the variable
on its right.

• Consider the following statements:

int temp ; // declaration of int type variable


cin >> temp ; // Input using cin object

• The second statement causes the program to wait for the user
to type in an integer number. The resulting number is placed
in the variable temp.
Example: Output/ Input using cout and cin objects
#include<iostream.h>
void main()
{
int x;
float f;
char c;
char str[20] ;
cout << “\n Enter the value of x: “; Sample output:
cin >> x ; Enter the value of x: 5
cout << “\n Enter the value of f:” ;
Enter the value of f: 4.5
cin >> f
Enter the value of c: y
cout << “\n Enter the value of c:”;
cin >> c; Enter the value of str: hello
cout << “\n Enter a string: “;
cin >> str ; The value of x = 5
cout << “\n The value of x = “ << x; The value of f = 4.5
cout << “\n The value of f = “ << f;
The value of c = y
cout << “\n The value of c = “ << c;
The value of str = hello
cout << “\n The value of str = “ << str;
}
Cascading of << and >> operators
• When the operator (<<) is used repeatedly in the cout statement, it is
called cascading of extraction or output operator.
• The insertion operator (>>) can be cascaded with cin in the same way,
allowing the user to enter a series of values:
Example:
#include<iostream.h>
void main()
{
int x, float f, char c, char str[20];
cout << “\n Enter the value of x, f, c and str “ ;
cin >> x >> f >> c >> str ; // Cascading of input operator
// Cascading of output operator
cout << “\n x = ” << x << “ f = ” << f << “ c= ” << c << “ str= ” << str ;
}
Sample Output:
Enter the value of x, f, c and str: 3 4.5 a hello
x = 3 f = 4.5 c = a str = hello
Flexibility in the declaration of the variables
• C requires that all variables be declared before the first
executable statement. As against this, C++ allows
definition of variables at the point where they are used. The
following example illustrates this:
#include<iostream.h>
void main()
{
int x , y ;
cout << “\n Enter the value of x: ” ;
cin >> x ;
cout << “\n Enter the value of y: ” ;
cin >> y;
int z ;
z = x + y;
cout << “\n The sum of the numbers is:” << z ;
}
Function Prototypes:
• A function prototype is one of the major improvement added to C++
function.

• The prototype describes the function interface to the compiler by


giving details such as: the number of arguments, the type of
arguments and the type of return value.

• The compiler uses the prototype to ensure that the types of actual
arguments that you pass in a function call are the same as the types
of the formal arguments in the function definition.

• No C++ function can be called unless its prototype is available to the


compiler to crosscheck the argument type and the return value. This
is known as strong type checking.

• Function prototype is a declaration statement in the calling program


and is of the following form:

return-type function_name (argument_list) ;


Example:
#include<iostream.h>
int sum(int, int); // Function prototype

void main()
{
int a = 4, b = 6;
int c = sum(a, b); // Calling function
cout << “\n The sum is: “<< c ;
}

// function definition
int sum(int x, int y)
{
int z = x + y ;
return z ;
}
Function overloading
• Overloading refers to the use of the same thing for different
purposes. C++ also permits overloading of functions.
Thus, one can use the same function name to create
functions that perform a variety of different tasks. This is
known as the function overloading in OOP.

• Using the concept of the function overloading, one 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.

• The correct function to be invoked is determined by


checking the number and the type of the arguments but not
on the function’s return type.
Example: function overloading
//Function Declarations
#include<iostream.h>
int sum( int , int ); //prototype1
int sum( int , int, int); //prototype2
float sum( float, int); //prototype3
int sum( char, char); //prototype4

void main()
{
int i1=5, i2 =6;
int i3 = sum(i1, i2); //Calling function1
int i4 = sum(i1, i2, i3); // Calling function2
float f1 = 4.5;
float f2 = sum(f1, i1); // Calling function3
char c1 =‘a’, c2 = ‘b’;
int c3 = sum(c1, c2); // Calling function4
cout << “i3 = “<< i3 ;
cout << “i4 = “ << i4 ;
cout << “f2 = “ << f2;
cout << c3 = “ << c3;
}
Cont.
// Function Definitions

int sum(int a, int b)


{
return (a + b);
}
int sum(int a, int b, int c)
{
return ( a + b + c ) ;
}
float sum(float f, int i)
{
return ( f + i) ; Sample Output:
}
i3 = 11
int sum(char c1, char c2)
{ i4 = 22
return (c1 + c2); f2 = 9.5
} c3 = 195
Reference in C++
• A reference, as the name suggests is like an alias.
It is similar to the pointer. A reference is
indicated by using the & operator in the same way
you use the * operator to indicate a pointer.

Segment1, using pointer Segment2, using reference


int a = 5; int a = 5;
int *p = &a; // p is a pointer to variable a int &p = a ; // p is a reference to variable a
cout << “*p = “ << *p ; cout << “\n p = “ << p ;

• A pointer has to be de-referenced before you can access


a value using it, while a reference need not be. (see the
third statements of each segment)
❖ A variable and its reference are so tightly inter-
locked, that a change in one necessarily results
in a change in the other.

#include<iostream.h>
void main()
{
int i = 10;
int &j = i ; // j is a reference to i
cout << “\n i = ” << i << “j = ” << j ; Output:
j = 20; i = 10 j = 10
cout << “\n i = ” << i << “j = ” << j ; i = 20 j = 20
i++;
i = 21 j = 21
cout << “\n i = ” << i << “j = ” << j ;
i = 22 j = 22
j++;
cout << “\n i= ” << I << “j = ” << j ;
}
Cont.

❖ A reference must always be initialized. Like pointers, it is


not possible to first declare the reference in one statement,
and then initialize it with the variable, in the next statement.

//Using reference //Using pointer


int a = 5 ; int a = 5 ;
int &p ; // error int *p ; // valid
p=a; p = &a;
❖ A variable can have multiple references. Changing the value
of one of them effects a change in all others.
#include<iostream.h>
void main()
{
int i = 5 ;
int &j = i ;
int &k =i ;
int &l = i ;
cout << “\n i = ” << i << “j = ” << j << “k = ”<< k << “l = ” << l;
k = 20;
cout << “\n i = ” << i << “j = ” << j << “k = ”<< k << “l = ” << l;
}
Output:
i=5 j=5 k=5 l=5
I = 20 j = 20 k = 20 l = 20
Cont.

❖ Once a reference variable has been defined to refer to a


particular variable, it cannot refer to any other variable.

❖ Though an array of pointers is acceptable, an array of


references is not.
❖ Referencing offers a clean, elegant an efficient way to pass
parameters to functions that intend to change their values.

#include<iostream.h>
void update1(int);
void update2(int*);
void update3(int&);
void main()
{
int i =j = k = 5;
update1(i) ; // Call by value
update2(&j); // Call by pointer
update3(k); // Call by reference
cout << “\n i = “ << i ;
cout << “\n j = “ << j ;
cout << “\n k = “ << k ;
}
Cont.
void update1(int i);
{
i = i + 1;
cout << “\n i = “ << i ;
}
void update2(int* j)
{
*j = *j + 1;
cout << “\n *j = “ << *j ;

}
void update3(int& c)
{
c = c + 1;
cout << “\n c = “ << c ;
}
const qualifier
• If the keyword const, precedes the data type of
a variable, the value of the variable will not
change throughout the program.

• Any attempt to alter the value of the variable


defined with this qualifier will result into an error
message from the compiler.

• The syntax is:


const data_type VAR_NAME = value ;
Example:
#include<iostream.h>
const float PI = 3.14 ;
void main()
{
float radius ;
cout << “\n Enter the radius :” ;
cin >> radius ;
float area = PI*radius*radius ;
cout << “\n Area of circle = ” << area ;
PI = PI +1 ; // Error! The symbolic constant cannot be modified

}
new and delete operators
• The dynamic memory allocation in C is done by using the
functions: malloc() and calloc().

• The memory allocated from system heap using malloc() and


calloc() is vacated (deallocated) using the function free().
• C++ Offers a better way to accomplish the same job through
the use of the new and delete operators.

• The new operator allocates memory from free store (in the
C++ lexicon, heap is called free store).

• The delete operator returns the allocated memory back to the


free store.

• The new operator, when used with the pointer to a data type,
a structure, or an array, allocates memory for the item and
assigns the address of that memory to the pointer. The delete
operator does the reverse.
Using new and delete operators
The general form of using new operator is:

data_type *variablename = new data_type ;

Eg:
int *p = new int ;
float *q = new float ;

*p = 25; // assigns 25 to the newly created int object


*q = 7.5; // assign 7.5 to the float object.

One can also initialize the memory using the new operator. This is
done as follows:
pointer_variable = new data_type(value); // Here, value specifies
// the initial value
Eg:
int *p = new int(25);

float *q = new float(7.5);


Cont.
When a data object is no longer needed, it can be
destroyed by the delete operator to release the memory
space for the reuse. The general form of its use is:
delete pointer-variable ;
Eg:
delete p ;
delete q ;
Allocating space for arrays, during run time
The general form of one dimensional array is:

data_type *poiter-variable = new data_type[size];

To free a dynamically allocated array, use the following form of delete:

delete [ ] pointer-variable ;
Eg:
int *p = new int[5]; //Creates a memory space for an array of 5 integers.

When creating multi-dimensional arrays with new, all the array sizes must
be supplied.

Eg:
array_ptr = new int[3][5][4] ; // legal
array_ptr = new int[m][5][4] ; // legal
array_ptr = new int[3]]5][ ] ; // illegal
array_ptr = new int[ ][5][4] ; // illegal
Cont.

• To free a dynamically allocated array, we


must use the following form of delete:
delete [ ] pointer-variable ;
Allocation and deallocation, [ using malloc() and free() functions in C ] and
[ new and delete operators in C++ ]
Using C
struct List Using C++
{ struct List
int data ; {
List* next ; int data ;
}; List* next;
void main() };
{ /* Allocating the space for one object of List void main()
type*/ { // Allocating space for one
struct List * node = (List*) // object of List type
malloc(sizeof(List)); List* node = new List ;
------- -------
------- -------
free(node); delete node ;
}
} int *p ;
int *p ; p=new int[5]; //Allocating
p = (int*)malloc(sizeof(int)*5); /* Allocating space space
------ for 5 integer elements // for 5 integer
*/ elements
------ ------
free(p); ------
Example: Allocating space for single-dimensional array of integers
#include<iostream.h>
void main( )
{
int n ;
cout << "\n Enter the size of array: ";
cin >> n ;
int *p = new int [n]; // Allocate the space for n integer elements
cout << "\n Enter the elements in the array: \n ";
for(int i = 0; i < n; i++)
{ Sample Output:
cout << "\n p[" << i << "] = " ;
Enter the size of array: 4
cin >> *(p+i);
} Enter the elements in the array:
for(i = 0; i < n; i++) p[0] = 6
{
p[1] = 4
cout << "\n The elements are: " ;
cout << *(p+i) ; p[2] = 3
} p[3] = 5
delete [ ] p; // Deallocate the space
The elements are: 6 4 3 5
}
Example: Allocating space for two-dimensional array of integers
#include<iostream.h>
void main()
{
int row, col ;
cout << "\n How many rows to enter: ";
cin >> row ;
cout << "\n How many columns to enter: " ;
cin >> col ;
int **a = new int *[row];
for(int i = 0; i < row; i++)
{
a[i] = new int[col];
for(int j = 0; j < col ; j++)
{
cout << "\n Enter the element at a[" << i << "] [" << j << "] = ";
cin >> *(*(a+i) + j);
}
}
Cont. Sample Output:
How many rows to enter: 3
cout << “\n The array is:\n”
for(i = 0; i < row; i++) How many columns to enter: 3
{ Enter the element at a[0][0] = 3
for(int j = 0; j < col; j++)
Enter the element at a[0][1] = 2
{
cout <<" " << *( *(a+i) + j ) ; Enter the element at a[0][2] = 1
} Enter the element at a[1][0] = 6
cout << endl;
Enter the element at a[1][1] = 3
}
for(i =0; i < row; i++) Enter the element at a[1][2] = 4
delete[ ] a[i]; Enter the element at a[2][0] = 9
delete[ ] a;
Enter the element at a[2][1] = 5
}
Enter the element at a[2][2] = 7
The array is:
3 2 1
6 3 4
9 5 7
Pointer to an array of pointers

You might also like