OOPs in C++ UNIT-I
OOPs in C++ UNIT-I
PROGRAMMING IN C++
[UNIT 1]
U1.1
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63 ,By Ritika Wason & Manu Anand 1
Learning Objectives
• Principles of Object-Oriented Programming Approach
• Object
• Classes
• Data Abstraction
• Data Encapsulation
• Inheritance
• Polymorphism
• Dynamic Binding
• Message Passing
• POP vs. OOPS
• Examples of Basic C++ Programs
U1.2
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
PROGRAMMING PARADIGMS
OBJECT-ORIENTED
A programming
PROGRAMMING
paradigm is a general
approach to
OBJECT-BASED PROGRAMMING programming or to the
solution of problems
using a programming
PROCEDURAL PROGRAMMING language. Thus
programming
ASSEMBLY LANGUAGE languages that share
similar characteristics
are clustered together
MACHINE LANGUAGE
in the same paradigm.
U1.3
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
PROGRAMMING PARADIGMS
The major paradigms are:
Procedural: Subroutines and global data items; eg: ALGO,
FORTRAN, BASIC and COBOL
Structured : Emphasis on algorithms rather than data; eg:
PASCAL and C
Object-based: Support object creation; eg: Modula-2
Object-oriented: Classes and objects; eg: C++,Smalltalk,
Eiffel and Java
Logical : Goals, often expressed in predicate calculus
Rule-based : if-then-else rules
Data base query languages: SQL
Visual: VB,VB C++
Scripts
Programming by Demonstration
U1.4
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Procedural Programming
• Divide a program into functions / subroutines/
procedures, also called Procedure Oriented
Programming (POP).
• Programs organized in the form of procedures and all
data items are global. Hence data is not protected.
• Program controls are through jumps (goto) and call to
the subroutine.
• As programs increase in complexity, management
becomes difficult.
• Subroutines are abstracted to avoid repetitions.
• Hierarchial in nature.
U1.5
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Procedural Programming
Advantages:
• Suitable for Medium sized applications.
• Minimize Duplication of data.
• Reduce errors.
• Saves time, money & space.
U1.6
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Procedural Programming
• Disadvantages:
• Since global data is accessible to all functions so the data
can be easily corrupted.
• Since many functions access the same data, the way the
data is stored becomes critical. The arrangement of the
data can not be changed without modifying all the
functions that access it.
• Like other traditional languages, Extensibility ( Creating
new data type) is not possible.
• Difficult to maintain/enhance the program code.
• Does not model real world very well.
U1.7
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Object Based Programming
U1.8
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Object Oriented Programming
• Object = Data + Methods.
• Problem is divided into Objects ( data structure with data
fields, methods and their interaction) rather than
Functions.
• It ties data more closely to the functions and does not
allow it to flow freely around the system [Data
Abstraction].
• Use Bottom-up program technique for program design.
• Objects communicate by sending message to one another.
• New data & functions can be easily added whenever
necessary. [Inheritance].
U1.9
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Object Oriented Programming
• Advantages:
• Increased programming productivity.
• Reusable Code.
• Decreased maintenance code.
• Greater speed.
• Lesser Complexities.
• Abstraction makes it possible to change the data
structure of an object, without affecting the
operation of the program.
U1.10
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
STRUCTURED VS. OBJECT-ORIENTED
• Program and data two basic elements of computation. Data
can exist without a program, but a program has no relevance
without data.
• Conventional high level languages stress on algorithms used
to solve a problem. Here, data are defined as global and
accessible to all parts of a program without any restriction,
hence reduced data security and integrity.
• Object-Oriented programming emphasizes on data rather
than the algorithm. Here, data is encapsulated with the
associated functions into an object.
• OOP is centered around the concepts of objects,
encapsulation, abstract data types, inheritance,
polymorphism, message based communication, etc.
U1.11
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Object-Based versus Object-Oriented
• Object-Based Programming usually refers to objects without
inheritance and hence without polymorphism, as in '83 Ada and
Modula-2. These languages support abstract data types (Adts) and
not classes, which provide inheritance and polymorphism.
• object-oriented = data abstractions + object types + type
inheritance. OR
Object-Oriented = Classes and Objects + Inheritance +
Communication with messages
The main difference between object oriented and object based
languages is object based languages doesn't support
Inheritance where as object oriented supports.
U1.12
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
FEATURES OF OOP
U1.13
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
HISTORY OF C++
U1.14
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
C versus C++
• C follows structured programming while C++ is object-oriented.
• C does not provide data abstraction, hence data is not secure. C++
provides data abstraction.
• C is mainly function driven, while C++ is object-driven.
• C++ supports function overloading, while C does not.
• C does not use namespaces to avoid name collisions while C++ does.
• Standard I/O differs in C and C++
• C++ allows use of reference variables while C does not.
• C++ supports exception handling while C does not.
• C++ is a superset of C, earlier called C with classes.
• Classes and inheritance are a major addition to C++.
• C programs can be compiled in C++ compiler.
U1.15
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Structure of C++ Program
U1.16
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Structure of C++ Program
/* greeting.cpp greets its user. * * Input: The name of the user * Output:
A personalized greeting */
#include <iostream> //preprocessor directive for iostream header file
#include <string> //preprocessor directives
int main()//main function declaration
{ //block scope
cout << "Please enter your first name: ";
string firstName;
cin >> firstName;
cout << "\nWelcome to the world of C++, "
<< firstName << "!\n"; return 0;}
U1.17
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
All the elements of the standard C++ library are declared within
what is called a namespace, the namespace with the name std. So
in order to access its functionality we declare with this expression
that we will be using these entities. This line is very frequent in
C++ programs that use the standard library, and in fact it will be
included in most of the source codes
U1.18
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
ANSI/ISO Standard C++
• International Standard for the C++ programming language is
ANSI/ISO/IEC 14882:1998 which first became a standard in 1998.
• It includes: Standard library: Header file names no longer maintain the .h
extension typical of the C language and of pre-standard C++ compilers
• Header files that come from the C language now have to be preceded by a
c character in order to distinguish them from the new C++ exclusive header
files that have the same name. For example stdio.h becomes cstdio
• All classes and functions defined in standard libraries are under the std
namespace instead of being global.
• Standard Template library: Wide range of collection classes
• Exception handling
• Namespaces
•
U1.19
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Comments
In C++, there are two different comment delimiters:
the comment pair (/*, */),
the double slash (//).
The comment pair is identical to the one used in C:
The sequence /* indicates the beginning of a comment.
The compiler treats all text between a /* and the following */ as a
comment.
A comment pair can be multiple lines long and can be placed
wherever a tab, space, or newline is permitted.
Comment pairs do not nest.
// serves to delimit a single line comment. Everything on the
program line to the right of the delimiter is treated as a comment
and ignored by the compiler.
U1.20
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Variables
a variable is a named location in memory that is used to hold a
value that may be modified by the program. All variables must
be declared before they can be used. The general form of a
declaration is
type variable_list;
Here, type must be a valid data type plus any modifiers, and
variable_list may consist of
one or more identifier names separated by commas. Here are
some declarations:
int i,j,l;
short int si;
unsigned int ui;
double balance, profit, loss;
U1.21
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Operating with Variables
// initialization of variables
#include <iostream>
using namespace std;
int main ()
{ o/p=6
int a=5; // initial value = 5
int b(2); // initial value = 2
int result; // initial value undetermined
a = a + 3;
result = a - b;
cout << result;
return 0;
}
U1.22
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
const
• Variables of type const may not be changed by
your program. (A const variable can be given an initial
value, however.) The compiler is free to place variables
of this type into read-only memory (ROM). For example,
• const int A=10;
• creates an integer variable called a with an initial value
of 10 that your program may not modify.
• They are treated just like regular variables except that
their values cannot be modified after their definition.
U1.23
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Stream Based I/O
C++’s feature for handling I/O operations are called streams
Streams are abstractions that refer to data flow.
Stream in C++ are classified into
Output Streams
Input Streams
• Output Stream performs write operations on output
devices
• Syntax is cout<< variable
• More than one item can be displayed using single output
stream object called cascaded output operations
cout<< “Age = “<< age;
U1.24
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Input Streams
• Perform read operation with input devices
• Performed using cin object
• extracts data from a stream and copies the extracted
information to variables
• skip all white space characters that precede the values to be
extracted
• Syntax: int age; cin >>age;
• Input of more than one item can also be performed using the
cin input stream object called cascaded input operations
cin >> name>> age;
• Object cin, must be associated with at least one argument.
U1.25
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Enumerated types
• An enumeration is a data type in which labels for all possible
values of the type can be listed
• The type declaration consists of the keyword enum followed by
the name of the new type and a block of code in which labels for
all values of the type are listed. Syntax:
enum NewTypeName {value1, value2, … , valueN};
• The value labels in an enumeration are called enumeration
constants. Enumeration constants must be valid C++ identifiers;
they are not string or char literals
• Enumeration constants are stored in memory as integers; by
default, the first is assigned the value 0, the second 1, etc.
• Thus the order of the listing determines the relative magnitude of
enumeration constant values; the first is less than the second,
which is less than the third, and so forth
U1.26
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Specifying different values in enumerations
• By default, the first enumeration constant has the value
0, the second 1, the third 2, etc.
• The default behavior can be overridden by assigning
explicit values to one or more of the constants
• For Ex: The following enumeration uses explicit
assignment to specify values for the symbols used in the
Roman numeral system:
enum RomanNum { I = 1, V = 5, X = 10, L = 50, C =
100, D = 500, M = 1000};
U1.27
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Example 2 (enum)
• The following enumeration type creates constants that
stand for the months of the year:
enum MonthType {JAN=1, FEB, MAR, APR, MAY,
JUN, JUL, AUG, SEP, OCT, NOV, DEC};
• Only the first constant’s value is specified; since it is 1,
the second is 2, the third is 3, and so on until the last
(DEC) with the value 12
U1.28
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Using enumerated types
• Enumerations only create new data types;
types to actually
store and use values of the new types, you must declare
variables
• Variables of each enum type can hold only those values
specified by the enumeration
• For example, with the MonthType enumeration, you
could declare variables and assign them values like the
following:
MonthType thisMonth = APR;
MonthType nextMonth = MAY;
MonthType birthMonth = nextMonth;
U1.29
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Operations on enumerations
• Since enumerations are not built-in data types, only some
of the most common operations can be performed using
variables of these types
• The allowable operations include:
logical comparison using the relational operators (<,
>, <=, >=, ==, !=)
simple arithmetic (but not arithmetic/assignment
operations like ++ or --)
enumerations can be parameters to, and/or return
values from, functions
enumerations can be used as switch expressions
and/or case labels in switches – example on next slide
U1.30
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
MonthType thisMonth;
…
switch ( thisMonth ) // using enum type switch expression
{
case JAN :
case FEB :
case MAR : cout << “Winter quarter” ;
break ;
case APR :
case MAY :
case JUN : cout << “Spring quarter” ;
break ;
case JUL :
case AUG :
case SEP : cout << “Summer quarter” ;
break ;
case OCT :
case NOV :
case DEC : cout << “Fall quarter” ;
}
U1.31
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Incrementing enum variables using type cast
mechanism
U1.32
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Using enum type Control Variable with for Loop
MonthType month ;
.
.
.
}
U1.33
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Simple arithmetic with enumeration constants
• Previously, we defined an enumeration of the symbols
used in the Roman numeral system
• We will use this enumeration to illustrate arithmetic with
enums, and see another example of type casting.
• Note: The insertion (<<) and extraction (>>) operators
are not defined for enum-type variables
• To perform input or output operations on user-defined
types, you must provide your own functions.
U1.34
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Example
#include <iostream.h>
#include <stdlib.h>
enum RomanNum {I=1, V=5, X=10, L=50, C=100, M=1000};
int main()
{
cout << "Welcome to the world of Roman numerals!" << endl;
int num = (int)(M + C + L + X + V + I);
cout << "MCLXVI=" << num << endl;
num = (int)((L-X) + (V-I));
cout << "XLIV=" << num << endl;
system("PAUSE");
return 0;
}
U1.35
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Arrays Hold Multiple values
• Unlike regular variables, arrays can hold multiple
values.
Array Declaration Number of Size of Size of the
Elements Each Element Array
36
U1.36
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
// This program asks the user for the number of hours worked
// by 6 employees. It uses a 6-element int array to store the
// values.
#include <iostream.h>
void main(void)
{
short hours[6];
cout << "Enter the hours worked by six employees: ";
cin >> hours[0];
cin >> hours[1];
cin >> hours[2];
cin >> hours[3];
37
U1.37
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Program continues
cin >> hours[4];
cin >> hours[5];
cout << "The hours you entered are:";
cout << " " << hours[0];
cout << " " << hours[1];
cout << " " << hours[2];
cout << " " << hours[3];
cout << " " << hours[4];
cout << " " << hours[5] << endl;
}
38
U1.38
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Array Initialization
• int A[5] = {2, 4, 8, 16, 32};
Static or automatic
• int B[20] = {2, 4, 8, 16, 32};
Unspecified elements are guaranteed to be zero
• int C[4] = {2, 4, 8, 16, 32};
Error — compiler detects too many initial values
U1.39
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Initializing Allocated Memory
• You can initialize allocated memory to some known
value by putting an initializer after the type name in
the new statement. Here is the general form of
new when an initialization is included:
• p_var = new var_type (initializer);
U1.40
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Allocating Arrays
You can allocate arrays using new by using this general
form:
p_var = new array_type [size];
Here, size specifies the number of elements in the array.To
free an array, use this form of delete:
delete [ ] p_var;
Here, the [ ] informs delete that an array is being released.
For example, the next program allocates a 10-element integer
array.
U1.41
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
No Bounds Checking
There are no checks in C++ that an array subscript is in
range
An invalid array subscript can cause program to
overwrite other memory
Example:
const int ISIZE = 3;
int i = 4;
int num[ISIZE];
num[i] = 25;
U1.42
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
// This program uses an array of ten characters to store the
// first ten letters of the alphabet. The ASCII codes of the
// characters are displayed.
#include <iostream.h>
void main()
{
char letters[10] = {'A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'I', 'J'};
cout << "Character" << "\t" << "ASCII Code\n";
cout << "--------" << "\t" << "----------\n";
for (int count = 0; count < 10; count++)
{
cout << letters[count] << "\t\t";
cout << int(letters[count]) << endl;
}
}
U1.43
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
// Precondition: n is a positive integer
// Postcondition: computes and prints out the first n
// elements of the Fibonacci sequence
void fibonacci(int n){
int *x = new int [n]; // creation of a dynamic array
x[0]=1; x[1]=1;
for (int i=2;i<n;i++)
x[i]=x[i-1]+x[i-2];
cout<<"The Fibonacci sequence of "<<n<<" values
are:\n";
for (int i=0;i<n;i++)
cout<<"x["<<i<<"]="<<x[i]<<endl; }
U1.44
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
//read values and print them in reverse
#include <iomanip.h>
void main()
{
int x[5], index;
cout << “Please enter five integer values: “;
for( index=0; index<5; index++) cin >> x[index];
cout << “The values in reverse order are: “;
for (index=4; index>=0; index--)
cout << setw(3) << x[index];
cout << endl;
}
U1.45
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Creating Multidimensional Arrays
int[][] matrix = new int[10][10];
or
int matrix[][] = new int[10][10];
matrix[0][0] = 3;
U1.46
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Arrays Example
#include <iostream> #include <new>
using namespace std;
int main()
{ int *p, i;
try {
p = new int [10]; // allocate 10 integer array
} catch (bad_alloc xa) {
cout << "Allocation Failure\n";
return 1; }
for(i=0; i<10; i++ )
p[i] = i;
for(i=0; i<10; i++)
cout << p[i] << " ";
delete [] p; // release the array
return 0;}
U1.47
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Introduction to Pointers
• When we declare a variable some memory is allocated for it. Thus,
we have two properties for any variable : its address and its data
value. The address of the variable can be accessed through the
referencing operator “&”.
• A pointer variable is one that stores an address. Ex: int* p; //This
means that p stores the address of a variable of type int.
• Q: Why is it important to declare the type of the variable that a
pointer points to? Aren’t all addresses of the same length?
• A: All addresses are of the same length, however when we perform an
operation of the type “p++” where “p” is a pointer variable, for this
operation to make sense the compiler needs to know the data type of the
variable “p” points to. If “p” is a character pointer then “p++” will
increment “p” by one byte (typically), if “p” were an integer pointer its
value on “p++” would be incremented by 2 bytes (typically).
U1.48
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Pointers and Arrays
• The concept of array is very similar to the concept of pointer.
The identifier of an array is actually a pointer that holds the
address of the first element of the array.
• Therefore if you have two declarations as follows:
“int a[10];” “int* p;” then the assignment “p = a;” is
perfectly valid
Also “*(a+4)” and “a[4]” are equivalent as are “*(p+4)”
and “p[4]” .
The only difference between the two is that we can change
the value of “p” to any integer variable address whereas
“a” will always point to the integer array of length 10
defined.
U1.49
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Character Pointers, Arrays and Strings
• What is a String?
A string is a character array that is ‘\0’ terminated.
E.g. “Hello”
• What is a Character array?
It is an array of characters, not necessarily ‘\0’ terminated
E.g. char test[4] = {‘a’, ‘b’, ‘c’, ‘d’}; <this char array is not
zero terminated>
• What is a character pointer?
It is a pointer to the address of a character variable.
E.g. char* a; <this pointer is not initialized>
U1.50
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Character Pointers, Arrays and Strings
• How do we initialize a Character pointer?
Initialize it to NULL. char* a = NULL;
Let it point to a character array.
char* a; char b[100]; a = b;
Initialize to a character string.
char* a = “Hello”; a pointer to the memory location where
‘H’ is stored. Here “a” can be viewed as a character array of
size 6, the only difference being that a can be reassigned
another memory location.
U1.51
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Examples
• char* a = “Hello”;
a -> gives address of ‘H’
*a -> gives ‘H’
a[0] -> gives ‘H’
a++ -> gives address of ‘e’
*a++ -> gives ‘e’
a = &b; where b is another char variable is perfectly
LEGAL. However “char a[100];” “a =&b;” where b is
another char variable is ILLEGAL.
U1.52
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Remember
• Pointer is a datatype that stores addresses.
• Values stored in a pointer are accessed through the
dereferencing operator “*”
• Address of a memory location of a variable can be
accessed through the reference operator &.
• Concept of array is similar to the concept of pointer.
• Identifier of an array is actually a pointer that holds the
address of first element of an array.
• Hence: int a[10]; int*p; p=a;
U1.53
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Void Pointers
• Pointers variables declared as void, hence can
accept data from any type of pointer.
• Ex: void*gp;
int *ip;
• ip= (int*) gp;
U1.54
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Constant Pointers
• Pointers for constants used in programs.
• char *const ptr={“GOOD”};
• //constant pointer with value GOOD
• int const*ptr1=&m;
• Pointer to a constant that accepts address of m variable.
Contents of such pointers cannot be changed.
U1.55
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Name and Address of an Array
• Name of an array in C++ is the starting address for that
array.
• Ex: char town[]=“Beijing”;
• Pointer to the first character of the string town is passed.
Characters forming the string are read and displayed
from this point onwards until the terminating null
character, ‘\0’ is reached.
U1.56
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
CLASSES IN C++
U1.57
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
STRUCTURE OF C++ PROGRAM
INCLUDE FILES
CLASS DECLARATION
U1.58
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
CLASS
• A class is a group of objects that share common
properties & behavior/ relationships.
• In fact, objects are the variables of the type class.
• After creating class, one can create any no. of related
objects with that class.
• Classes are user defined data types and behaves like
the built-in types of a programming language.
U1.59
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
MYCLASS1.CPP
// myclass1.cpp
#include <iostream.h>
class myclass1// class starts the declaration of a new class
{
private: //Data members are usually private
int num;
public: // Member functions are public in nature.
void getdata() // to enter the value
{
cout<<“Enter an integer:”;// cout keyword to display information
cin>>num; // cin is the keyword to enter data
}
U1.60
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
MYCLASS1.CPP
void dispdata() // to display the value
{
cout<<“Num=“ <<num<<endl;
}
}; // indicates the end of class command.
void main()
{myclass1 a1, b1; / /a1 & b1 are objects of class myclass1.
a1.getdata();
b1.getdata();
a1.dispdata();
b1.dispdata();
}
U1.61
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Class Example
// example: class constructor CRectangle::CRectangle (int a, int b)
#include <iostream> {
using namespace std; width = a;
class CRectangle height = b;
{ }
int width, height; int main ()
public: {
CRectangle (int,int); CRectangle rect (3,4);
int area () CRectangle rectb (5,6);
{ cout << "rect area: " << rect.area() <<
return (width*height); endl;
} cout << "rectb area: " << rectb.area() <<
}; endl;
return 0;
}
U1.62
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Try Out Yourself?
1.Write a program to define a class student. Write function to take
the information from user and display the information to user.
2.Write program for a library database using class and with the
following data items:
Title of Book
Acc Number
Author
Publisher
Price
U1.63
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Try out Yourself?
Create a class employee which have name, age and address of the
employee. Include functions getdata() and showdata(). Showdata takes
the input from the user and display on the monitor in a tabular format
and use inline with getdata().
Name:
Age:
Address:.
U1.64
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Class Diagram of Employee class
Class: employee
Data:
Name
Dept
Desig
Basic
Functions:
Setbp( )
Totsal( )
Deductions( )
U1.65
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
ABSTRACTION
• It refers to the act of representing essential
features without including the background details
or explanations.
• Explanation (Driving a Car):
U1.66
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
ENCAPSULATION
• The wrapping up of data & functions (that
operate on the data) into a single unit (called
class) is known as ENCAPSULATION.
• Encapsulation is a way to implement data
abstraction.
• Only Relevant details are exposed and rest are
made hidden. [Data Security]
• Example: Departmental data, ATM cash counter,
Weighing Machine etc.
U1.67
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
MODULARITY
• The act of partitioning a program into individual
components i.e. into a set of cohesive and loosely
couple modules.
U1.68
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Contd.
Advantages:
• It reduces the complexity of a system to a
greater extent.
• It creates a number of well defined
document boundaries within the program.
• Makes data secure.
• Faster speed.
• Debugging easier.
U1.69
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
INHERITANCE
• Inheritance is the capability of one class of
things to inherent properties from other class.
• Supports the concept of Hierarchical
classification.
• Ensures the closeness with real world models.
• Provides Multiple Access Specifiers across
the modules (Public, Private & Protected)
• Supports Reusability that allows the addition
of extra features to an existing class without
modifying it.
U1.70
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
U1.71
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
U1.72
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Public, Protected, Private Inheritance
class A { • Class A declares 3 variables
public: i is public to all users of class A
int i; j is protected. only be used by methods in class
protected: A or its derived classes
int j; k is private. It can only be used by methods in
private: class A
int k; • Class B inherits publicly from A
}; i is again public to all users of class B, while j
Class B : public A { // ... is again protected. It can be used by methods
}; in class B or its derived classes
Class C : protected A {// ... • Class C uses protected inheritance from A
}; i is now protected in C, so the only users of
Class D : private A {// ... class C that can access i are the methods of
}; class C
j is again protected. It can be used by methods
in class C or its derived classes
• Class D uses private inheritance from A
i and j are private in D, so users of D cannot
access them, only methods of D itself
U1.73
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
POLYMORPHISM / OVERLOADING
• A Greek term suggest the ability to take more than one form.
• Typically occurs when there is a hierarchy of classes related
by inheritance.
• Simply implies that call to a member function will cause a
different object to be executed, depending on the type of
object that invokes the function.
• It is a property by which the same message can be sent to the
objects of different class.
Example: Draw a shape (Box, Triangle, Circle etc.), Move
( Chess, Traffic, Army).
U1.74
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Need???
It simplifies the programming interface.
It permits conventions to be established that can
be reused in class after class.
Instead of inventing a new name for each new
function you add to a program the same names
can be reused.
The programming interface can be described as
a set of abstract behaviors quite apart from the
classes that implement them.
U1.75
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
U1.76
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Compile time polymorphism
involves binding of functions based on the
number of arguments,
type of arguments
sequence of arguments.
This information is known to the compiler at compile time. So
compiler selects the appropriate function for a particular call at
compile time itself.
The various parameters are specified in the function
declaration, and therefore the function can be bound to calls at
compile time.
This form of association is called early binding. The term early
binding implies that when the program is executed, the calls
are already bound to the appropriate functions.
U1.77
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Function overloading
#include <iostream>
using namespace std;
class arith {
public: void calc(int num1)
{cout<<"Square of a given number: " <<num1*num1 <<endl;}
void calc(int num1, int num2 )
{cout<<"Product of two whole numbers: " <<num1*num2 <<endl;
}};
int main() //begin of main function
{
arith a;
a.calc(5);
a.calc(6,7);}
U1.78
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Runtime Polymorphism
refers to an entity changing its form depending on
circumstances.
A function is said to exhibit dynamic polymorphism when it
exists in more than one form, and calls to its various forms are
resolved dynamically when the program is executed.
The term late binding refers to the resolution of the functions
at run-time instead of compile time. This feature increases the
flexibility of the program by allowing the appropriate method
to be invoked, depending on the context.
U1.79
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
virtual member function?
• A virtual function allows derived classes to replace or redefine the
implementation provided by the base class.
• The compiler makes sure the replacement is always called whenever the
object in question is actually of the derived class, even if the object is
accessed by a base pointer rather than a derived pointer.
• This allows algorithms in the base class to be replaced in the derived class,
even if users don't know about the derived class.
We can say shortly that:
The virtual keyword indicates to the compiler that
it should choose the appropriate definition of a function not by
the type of reference, but by the type of object that the reference
refers to.
For this it uses concepts of dynamic binding.
U1.80
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Dynamic binding
• Means that the address of the code in a member function
invocation is determined at the last possible moment based on
the dynamic type of the object at run time.
• Syntax:
prefix declaration with the virtual keyword
redefine a virtual member function in any derived class
this is called overriding
Example:
class A { public:
virtual void f() { cout << "Class A" << endl;} };
class B: public A {
public:
void f(int) { cout << "Class B" << endl; }};
U1.81
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Contd…
overridden function must have same name and same
parameter list
no need to use the virtual keyword again
return type can be different
if the parameter lists are different, they are considered
different
in this case, it is not overridden, but hidden
hidden methods cannot be called
U1.82
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Class, Objects and Memory Resources
• When an object is created, memory is allocated only to its
data members and not to member Function.
U1.83
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Constructors that Allocate Memory Dynamically
[Dynamic Constructors]
• Constructors can be used to initialize member objects as well
as to allocate memory. Memory allocation at run-time is
also known as dynamic memory allocation.
• C++ provides two dynamic allocation operators: new and
delete. These operators are used to allocate and free memory
at run time.
• C++ also supports dynamic memory allocation functions,
called malloc( ) and free( ). These are included for the sake
of compatibility with C.
• The new operator allocates memory and returns a pointer
to the start of it. The delete operator frees memory
previously allocated using new.
• Overloading of new and delete operator is possible
U1.84
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Dynamic Allocation Operators
• delete is a keyword and the pointer variable is the pointer that
points to the objects already created in the new operator.
• We know that sizeof operator is used for computing the size of the
object. Using memory management operator, the size of the object is
automatically computed.
• Null pointer is returned by the new operator when there is insufficient
memory available for allocation.
• new automatically allocates enough memory to hold an object of
the specified type. You do not need to use the sizeof operator.
Because the size is computed automatically, it eliminates any
possibility for error in this regard.
• new automatically returns a pointer of the specified type. You
don't need to use an explicit type cast as you do when allocating
memory by using malloc( ).
U1.85
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Dynamic Allocation Operators
• Pointer to objects of class, pointing to statically created objects.
• Sample *ptr; Sample obj;
• ptr=&obj;
• ptr->x;
• ptr->get();
• Pointer to objects of the class,pointing to dynamically created
objects.
• Sample *ptr; ptr=new Sample;
• ptr->x;
• Ptr->get();
Delete ptr;
U1.86
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Dynamic Allocation Operators
•The general forms of new and delete are shown here:
p_var = new type;
delete p_var;
U1.87
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Dynamic Allocation Operators
The trouble is that not all compilers, especially older ones, will
have implemented new in compliance with Standard C++.
When C++ was first invented, new returned null on failure.
Later, this was changed such that new caused an exception on
failure. Finally, it was decided that a new failure will generate
an exception by default, but that a null pointer could be
returned instead, as an option.
U1.88
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Dynamic Allocation Operators
int * b= new int [5];
•In this case, the system dynamically assigns space
for five elements of type int and returns a pointer
to the first element of the sequence, which is
assigned to b. Therefore, now, b points to a valid
block of memory with space for five elements of
type int.
•The first element pointed by b can be accessed
either with the expression b[0] or the expression *b.
Both are equivalent.
•The second element can be accessed either with
b[1] or *(b+1) and so on...
U1.89
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
This program gives the allocated integer an initial value of 87:
#include <iostream> #include <new>
using namespace std;
int main()
{int *p;
try {p = new int (87); // initialize to 87
} catch (bad_alloc xa) {
cout << "Allocation Failure\n";
return 1;}
cout << "At " << p << " ";
cout << "is the value " << *p << "\n";delete p; return 0;}
U1.90
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Compound Assignment Operator
// compound assignment operators
#include <iostream>
using namespace std;
int main ()
{
int a, b=3;
a = b;
a+=2; // equivalent to a=a+2 O/P=5
cout << a;
return 0;
}
U1.91
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Conditional Operator
Conditional operator ( ? )
The conditional operator evaluates an expression returning a value
if that expression is true and a different one if the expression is
evaluated as false. Its format is:
U1.93
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Nesting of member function
Member function can be called by using its name inside another
member function of the same class.
#include<iostream.h> #include<conio.h>
class student void student::displaydata()
{ int age; {
char name[30]; cout<<"\n\n name is:"<<name;
public: cout<<"\n age is:"<<age;}
void getdata();
void displaydata();}; void main()
void student::getdata() {
{ cout<<"\n enter the name:"; student s;
cin>>name; s.getdata();
cout<<"\n enter the age:"; }
cin>>age;
displaydata();}
U1.94
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Nested class
:Class within the class and its calling method.
#include<iostream.h> #include<conio.h>
class report
{ int roll_no;char name[30], branch[30];
class dob
{ int dd, mm,yyyy;
public:
void get()
{cin>>dd>>mm>>yyyy; }
void display()
{ cout<<dd<<"-"<<mm<<"-"<<yyyy; }
}dob;
public:
void getdata();
void displaydata();};
U1.95
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
void report::getdata()
{cout<<"\nenter the roll no:"; cin>>roll_no;
cout<<"\nenter the name:"; cin>>name;
cout<<"\nenter the branch alloted:"; cin>>branch;
cout<<"\nenter the date of birth:";
dob.get();}
void report::displaydata()
{ cout<<"\n\nrollno\tname\tdate of birth\t branch alloted\n";
cout<<roll_no<<"\t"<<name<<"\t";
dob.display(); cout<<"\t\t"<<branch; }
void main()
{ report r;
r.getdata();
r.displaydata();
}
U1.96
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Inline Functions
•As you probably know, each time a function is called, a significant
amount of overhead is generated by the calling and return
mechanism. Typically, arguments are pushed onto the stack and
various registers are saved when a function is called, and then
restored when the function returns. The trouble is that these
instructions take time.
U1.97
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
#include <iostream> As far as the compiler is concerned,
using namespace std; the preceding program is equivalent to
inline int max(int a, int b) this one:
{ #include <iostream>
return a>b ? a : b; using namespace std;
} int main()
int main() {
{ return 0; cout << (10>20 ? 10 : 20);
cout << max(10, 20); cout << " " << (99>88 ? 99 : 88);
cout << " " << max(99, 88);
return 0; }
}
U1.98
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Inline functions may be class
Inline Functions
member functions. For example,
this is a perfectly valid C++ // Create another inline function.
program: inline void myclass::show()
#include <iostream> {
using namespace std; cout << a << " " << b << "\n";
class myclass {
}
int a, b;
public: int main()
void init(int i, int j); {
void show(); myclass x;
}; x.init(10, 20);
// Create an inline function. x.show();
inline void myclass::init(int i, int j) return 0;
{
}
a = i;
b = j;
}
U1.99
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Defining Inline Functions Within a Class
When a function is defined inside a class declaration, it is
automatically made into an inline function. It is not necessary (but
not an error) to precede its declaration with the inline keyword.
U1.100
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Constructors
A constructor is a special function that is a member of a class and has
the same name as that class. For example,
// This creates the class stack.
class stack {
int stck[SIZE]; int tos;
public:
stack(); // constructor
void push(int i);int pop();};
Notice that the constructor stack( ) has no return type specified. In
C++, constructors cannot return values and, thus, have no return type.
The stack( ) constructor is coded like this:
// stack's constructor
stack::stack()
{tos = 0;cout << "Stack Initialized\n";
}
U1.101
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Destructors
The complement of the constructor is the destructor.
There are many reasons why a destructor may be needed. For
example, an object may need to deallocate memory that it
had previously allocated or it may need to close a file that
it had opened.
In C++, it is the destructor that handles deactivation events.
The destructor has the same name as the constructor, but it is
preceded by a ~
. For example, here is the stack class and its constructor
and destructor.
U1.102
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
// stack's constructor
This creates the class stack.
class stack {
stack::stack()
int stck[SIZE]; {
int tos; tos = 0;
public: cout << "Stack Initialized\n";
stack(); // constructor }
~stack(); // destructor // stack's destructor
void push(int i);
int pop();
stack::~stack()
}; {
cout << "Stack Destroyed\n";
}
Notice that, like constructors,
destructors do not have return values.
U1.103
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Some important points about constructors:
U1.104
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Destructors
U1.105
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Overloading Constructors
U1.106
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Default Function Arguments
• C++ allows a function to assign a parameter a default value when no
argument corresponding to that parameter is specified in a call to that
function. The default value is specified in a manner syntactically
similar to a variable initialization.
• For example, this declares myfunc( ) as taking one double
argument with a default value of 0.0:
void myfunc(double d = 0.0)
{// ...
}
Now, myfunc( ) can be called one of two ways, as the following
examples show:
myfunc(198.234); // pass an explicit value
myfunc(); // let function use default
U1.107
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Example To Develop An Employee Class
/* class employee stores employee information. We use calc()
function to return average salary. */
#include <iostream> #include <string> // to use strings
class employee
{private:
int emp_no, basic;
char name[20];
public:
void getdata() // to enter the data
{cout<<“Enter Employee No:”; cin>>emp_no;
cout<<“Enter name:”; cin.getline(name,’\n’);
cout<<“Enter Salary: “; cin>>basic;}
U1.108
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Example To Develop An Employee Class
For example:
#define PI 3.14159
#define NEWLINE '\n'
U1.110
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
// defined constants: calculate circumference
#include <iostream>
using namespace std;
#define PI 3.14159
#define NEWLINE '\n'
int main ()
{
double r=5.0; // radius
double circle;
circle = 2 * PI * r;
cout << circle;
cout << NEWLINE;
return 0;
}
U1.111
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
U1.112
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Variable Aliases- Reference Variables
• Reference variable acts as an alias for the other value variables enjoys
the simplicity of value variable and power of the pointer variable
• Syntax
Datatype & ReferenceVariable = Value Variable
Ex: char & ch1 = ch;
• References must be initialized to refer to something.
• There is no such thing as a 0 reference.
• Once bound to a variable there is no way to make the reference refer
to something else.
• There is no such thing as "reference arithmetic."
U1.113
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Reference Variables contd..
• You cannot get the address of a reference. You can try to,
but what you get is the address of the variable referred to.
• No alias for constant value
int &num = 100 //invalid
• not bounded to a new memory location, but to the
variables to which they are aliased
• Function in C++ take arguments passed by reference
U1.114
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Reference Variables cont..
#include <iostream.h>
cout <<a;
void main(){
int a = 2; a=5;
int c = 7; int* b = &a;
int& x = a; cout<<a;
cout<<a; b = &c;
x = c;
cout <<*b;}
U1.115
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
#include <iostream.h>
void swap1(int * a, int*b){ void main(){
int temp = *a; int i =5;
*a = *b; int j = 10;
*b = temp;
return;} cout<< i <<" "<<j<<"\n";
void swap2(int & a, int& b){ swap1(&i, &j);
int temp = a; cout<< i <<" "<<j<<"\n";
a = b;
swap2(i, j);
b = temp;
return;} cout<< i <<"
"<<j<<"\n";}
U1.116
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Return by reference
• Suppose we want to return the Max element, but prohibit the caller
from changing it. Then we use a constant reference return:
const int & max(int & x, int & y)
void main(){
int a,b,c;
#include <iostream.h>
int & max(int & x, int & y)
cout<<”enter <a,b>:”;
{ cin>>a>>b;
if (x>y)
return x;
max(a,b) = 425;
else cout<<”a=”<<a;
return y;
Cout<<” b= “<<b;}
}
U1.117
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
C++ Structures: Classes
• In C++, the concept of structure has been generalized in an object-
oriented sense:
classes are types representing groups of similar instances
each instance has certain fields that define it (instance
variables)
instances also have functions that can be applied to them
(represented as function fields) -- called methods
the programmer can limit access to parts of the class (to only
those functions that need to know about the internals)
U1.118
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Structs in C++
• The C++ class is an extension of the C language structure.
• The only difference between a structure and a class is that
structure members have public access by default and class
members have private access by default, you can use the
keywords class or struct to define equivalent classes.
• class X { // private by default
int a;
public: // public member function
int f() { return a = 5; }; };
• struct Y { // public by default
int f() { return a = 5; };
private: // private data member
int a; };
U1.119
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Static Instance Variables
• C++ classes may also contain, static instance fields -- a single field
shared by all members of a class
• Often used when declaring class constants (since you generally only
need one copy of a constant)
• To make a field static, add the static keyword in front of the field
can refer to the field like any other field (but remember,
everybody shares one copy)
static variables are also considered to be global, you can refer to
them without an instance
static fields can be initialized (unlike other fields)
Ex: static int n=9;
• One can examine public static fields of a class outside of that class
using the form:
ClassName::StaticFieldName
U1.120
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
C++ Strings
• Examples:
string s1; // s1 = ""
string s2( "abcdef" ); // s2 = "abcdef"
string s3( s2 ); // s3 = "abcdef"
string s4( s2, 1 ); // s4 = "bcdef"
string s5( s2, 3, 2 ); // s5 = "de"
string s6( 10, '-' ); // s6 = "----------"
The string class also has a destructor that takes care of
freeing the memory storing the characters when the
object is destroyed.
U1.122
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Strings
• Constant Member Functions: do not modify the string.
• const char * data () - returns a C-style null-terminated string
• unsigned int length () - returns the length of the string
• unsigned int size () - returns the length of the string
• bool empty () - returns true if the string is empty, false otherwise
• Operators Defined for string:
• Assign =
string s1; string s2; s1 = s2; // the contents of s2 is copied to s1
• Append +=
string s1( "abc" ); string s2( "def" ); s1 += s2; // s1 = "abcdef" now
• Indexing []
string s( "def" ); char c = s[2]; // c = 'f' now
U1.123
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
String
• Concatenate +
string s1( "abc" ); string s2( "def" );
string s3 = s1 + s2; // s3 = "abcdef" now
• Equality ==
string s1( "abc" ); string s2( "def" );
bool flag1 = ( s1 == s2 ); // flag1 = false now
• Inequality != - the inverse of equality
• Comparison <, >, <=, >= - performs case-insensitive comparison
string s1 = "abc"; string s2 = "ABC";
bool flag1 = ( s1 < s2 ); // flag1 = false now
U1.124
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
•
Member
void swap ( other_string )
Functions:
- swaps the contents of onestring with the contents of other_string.
string s1( "abc" ); string s2( "def" );s1.swap( s2 );
• string & append ( other_string ) //appends other_string to this string, and
returns a reference to the result string.
• string & insert ( position, other_string ) // inserts other_string into this
string at the given position, and returns a reference
• string & erase ( position, count )
- removes count characters from this string, starting with the character at the
given position. If count is omitted the characters up to the end of the string
are removed. If both position and count are omitted the string is cleared.
• unsigned int find ( other_string, position )
• string substr ( position, count )
-
U1.125
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Pass-by-Value
• A function can be invoked in two manners viz. pass-by-value
and pass-by-reference . The pass-by-value method copies the
actual parameters into the formal parameters, that is, the
function makes its own copy of the argument and then uses
them.
• The main benefit of call-by-value method is that the original
copy of the parameters remains intact and no alteration by the
function is reflected on the original variable. All execution is
done on the formal parameters; hence, it insures the safety of
the data.
• The drawback of call-by-value is that a separate copy of the
arguments is used by the function, which occupies some
memory space thus increasing the size of the program.
U1.126
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Call-By-Reference
• The call by reference uses a different mechanism. In place of
passing value to the function, which is called, a reference to
the original variable is passed.
• A reference is an alias for the predefined variable. That is, the
value of that variable can be accessed by using any of the two:
the original or the reference variable name.
• When a function is called by reference, then the formal
parameters become reference to the actual parameters in the
calling function. This means that, in call by reference method,
the called function does not create its own copy of the original
values, rather, it refers to the original values only by different
names.
• This called function works with the original data and any
change in the value is reflected back to the data.
U1.127
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Call-By-Reference in Functions
We use & to denote a parameter that is passed by reference:
<data type> &<variable name>
Example:
void Increment(int &Number) ;
void SumAverage (double, double, double &, double &) ;
U1.128
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Pass by Value / Pass by Reference
This program uses two functions, one using pass-by-value
method and the other using pass-by-reference method.
This shows how the value of number does not change in
the main function, when it is evaluated using pass-by-
value method and on the other hand it changes when
implemented using pass-by-reference method.
U1.129
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Review Questions [Objective Types]
1. Is it appropriate to call C++ as “better C”?
2. What is the purpose of abstraction in C++?
3. Why do people change over from structured
programming to object programming approach?
4. Is it necessary to use encapsulation feature to create
class?
5. What is the difference between Visual Basic and Visual
C++?
6. Inspite of so many object oriented languages, why did
C++ become more popular?
U1.130
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Review Questions [Objective Types]
7. What is the difference between an object based
language and an object-oriented language?
8. What is the advantage of separating an interface from
its implementation?
9. What is the concept of multiple inheritance?
10. I keep hearing that in structured programming data is
given a step motherly treatment and the whole
emphasis on doing thing. What that does mean in
programmer’s language?
U1.131
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Review Questions [Short Answer Types]
U1.132
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Review Questions [Short Answer Types]
U1.134
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand
Review Questions [Long Answer Types]
U1.136
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63,by Ritika Wason & Manu Anand