0% found this document useful (0 votes)
56 views149 pages

C++ Ppts

The document provides an overview of C++, including: - What object-oriented programming is and the differences between procedural and object-oriented programming approaches. - The key concepts of object-oriented design like encapsulation, abstraction, inheritance and polymorphism. - An introduction to classes in C++, including the syntax for class declarations and how objects are instantiated from classes. - Other C++ concepts covered include function overloading, namespaces, console I/O, comments, and the differences between C and C++. Constructors and destructors are introduced as special member functions for initializing and cleaning up class objects.

Uploaded by

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

C++ Ppts

The document provides an overview of C++, including: - What object-oriented programming is and the differences between procedural and object-oriented programming approaches. - The key concepts of object-oriented design like encapsulation, abstraction, inheritance and polymorphism. - An introduction to classes in C++, including the syntax for class declarations and how objects are instantiated from classes. - Other C++ concepts covered include function overloading, namespaces, console I/O, comments, and the differences between C and C++. Constructors and destructors are introduced as special member functions for initializing and cleaning up class objects.

Uploaded by

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

AN OVERVIEW

OF C++
OBJECTIVES
 Introduction
 What is object-oriented programming?

Object Oriented Design


 Two versions of C++
 C++ console I/O
 C++ comments
 Classes: A first look
 Some differences between C and C++
 Introducing function overloading
 C++ keywords
 Introducing Classes
IN T R O D U C T I O N
 C++ is the C programmer’s answer to
Object-Oriented Programming
(OOP).
 C++ is a n enhanced version of the C

language.
 C++ adds support for OOP without

sacrificing any of C’s power, elegance, or


flexibility.
 C++ was invented in 1979 by Bjarne

Stroustrup a t Bell Laboratories in


Murray Hill, New Jersey, USA.
IN T R O D U C T I O N (CONT.)
 The elements of a computer language do not exist
in a void, separate from one another.
 The features of C++ are highly integrated.

 Both object-oriented and non-object-oriented

programs can be developed using C++.


Procedure oriented vs Object Oriented Programming
Procedure Oriented Object Oriented
Programming Programming
• This approach is also known • This approach is also
as the top-down approach. known as Bottom-up
• In this approach, a program Approach
is divided into functions that • The OOP concept was
perform specific tasks. basically designed to
• This approach is mainly overcome the drawbacks
used for medium-sized of Procedure oriented
applications. Data is global, programming which is
and all the functions can not so close to real-world
access global data. applications.
• The basic drawback of the • OOP allows writing of
procedural programming programs with the help of
approach is that data is not certain classes and real-
secured because data is time objects. It is very
global and can be accessed close to the real-world
by any function.  and its applications
Object Oriented Design
Designing systems with self contained objects and object classes
WHAT IS OOP?
 OOP is a powerful way to approach the
task of programming.
 OOP encourages developers to decompose

a problem into its constituent parts.


 Each component becomes a self-contained

object t h a t contains its own instructions


and d at a t h a t relate to t h a t object.
 So, complexity is reduced and the

programmer can manage larger programs.


WHAT IS OOP? (CONT.)

DATA ABSTRACTION:
The act of representing essential features with out including back
ground details (Hiding the actual content and showing only the required
content is said to be abstraction).
Example: index of text book, google search engine etc.,,
Advantage of abstraction is every user will get his/her own view of the
data.
DATA ENCAPSULATION:
Binds together code and data
Wrapping (combining) up of data and function into a single unit is
called as encapsulation.
Data will be not accessible to external classes. Only those functions that
are present in that class can access that data.
WHAT IS OOP? (CONT.)

 Polymorphism
 Allows one interface, multiple methods
 Inheritance : Property by which a new class
acquires the properties of existing class
 Provides hierarchical classification
 Permits reuse of common code an d d a t a
TWO V E R S IO N S OF C++
 A traditional-style C++ program -

#include <iostream.h>

int main()
{
/* program code */
return 0;
}
TWO V E R S IO N S OF C++ (CONT.)
 A modern-style C++ program t h a t uses the new-
style headers and a namespace -

#include <iostream>
using namespace std;

int main()
{
/* program code */
return 0;
}
THE NEW C++ HEADERS
 The new-style headers do not specify filenames.
 They simply specify standard identifiers t h a t

might be mapped to files by the compiler,


but they need not be.
 <iostream>
 <vector>
 <string>, not related with <string.h>
 <cmath>, C++ version of <math.h>
 <cstring>, C++ version of <string.h>
 Programmer defined header files should end in
“.h”.
S C O P E R E S O L U T I O N O P E R ATO R
(::)
 Unary Scope Resolution Operator
 Used to access a hidden global variable
 Example: usro.cpp
 Binary Scope Resolution Operator
 Used to associate a member function with its
class (will be discussed shortly)
 Used to access a hidden class member variable
(will be discussed shortly)
 Example: bsro.cpp
N AMES P ACES
 A namespace is a declarative region.
 It localizes the names of identifiers to avoid name
collisions.
 The contents of new-style headers are placed in
the s t d namespace.
 A newly created class, function or global variable
can put in a n existing namespace, a new
namespace, or it may not be associated with any
namespace
 In the last case the element will be placed in the global
unnamed namespace.
 Example: namespace.cpp
C++ C O N SO L E I/O (O U T P U T )
 cout << “Hello World!”; cout ???
 printf(“Hello World!”);
 cout << iCount; /* int Shift right operator ???
iCount */ How does a shift right
printf(“%d”, iCount);

operator produce output
 cout << 100.99;
 printf(“%f”, 100.99); to the screen?
 cout << “\n”, or cout << ‘\n’, or cout <<
endl
 printf(“\n”)
 In general, cout << expression;

Do we smell polymorphism here??? 1


C++ C O N SO L E I/O (INPUT)
 cin >> strName; /* char strName[16] */
 scanf(“%s”, strName);
 cin >> iCount; /* int iCount */
 scanf(“%d”, &iCount);
 cin >> fValue; /* float fValue */
 scanf(“%f”, &fValue);
 In general, cin >> variable;

Hmmm. Again polymorphism.


C++ C O N SO L E I/O (I/O CHAINING)
 cout << “Hello” << ‘‘ << “World” << ‘!’;
 cout << “Value of iCount is: ” << iCount;

 cout << “Enter day, month, year: ”;

 cin >> day >> month >> year;


 cin >> day;
 cin >> month;

 cin >> year

What’s actually happening here? Need to learn


mor14e.
C++ C O N SO L E I/O (EXAMPLE)
include <iostream> include <iostream>
int main() using namespace std;
{ int main()
char str[16]; {
std::cout << “Enter a char str[16];
string: ”; cout << “Enter a string:
std::cin >> str; ”; cin >> str;
std::cout << “You entered: cout << “You entered: ”
” << str; << str;
} }
C++ COMMENTS
 Multi-line comments
 /* one or more lines of comments */
 Single line comments
 // …
CLASSES: A FIRST L O O K
 General syntax -

class class-name
{
// private functions and variables
public:
// public functions and variables
}object-list (optional);
CLASSES: A FIRST L O O K (CONT.)
 A class declaration is a logical abstraction
t h a t defines a new type.
 It determines what a n object of t h a t type
will look like.
 An object declaration creates a physical
entity of t h a t type.
 That is, a n object occupies memory space,
but a type definition does not.

CLASSES: A FIRST L O O K (CONT.)
 Each object of a class has its own copy of every
variable declared within the class (except
static variables which will be introduced
later), but they all share the same copy of
member functions.
 How do member functions know on which object they
have to work on?
 The answer will be clear when “this” pointer is introduced.
SOME DIFFERENCES
BETWEEN C A N D C+
+No need to use “void” to denote empty parameter

list.
 All functions m ust be prototyped.

 If a function is declared as returning a value, it

m u s t re t ur n a value.
 Return type of all functions m us t be declared

explicitly.
 Local variables can be declared anywhere.

 C++ defines the bool datatype, and

keywords
t r u e (any nonzero value) and false (zero).
I N T R O D U C I N G FUNCTION
OVERLOADING

Provides the mechanism by which C++ achieves one


type of polymorphism (called c ompi le -time
polymorphism).
 Two or more functions can share the same nam e as

long as either
 The type of their arguments differs, or
 The number of their arguments differs, or
 Both of the above
I N T R O D U C I N G FUNCTION
OVERLOADING (CONT.)
 The compiler will automatically select the correct
version.
 The r e t ur n type alone is not a sufficient

difference to allow function


overloading.

C++ K EY WO RDS (PARTIAL LIST)
 bool  protected
 catch  public

 delete  template

 false  this

 friend  throw

 inline  true

 namespace  try

 new  using

 operator  virtual

 private  wchar_t
INTRODUCING
CLASSES
C O N S T R U C TO R S
 E very object we cr eat e will r equ ir e some sort of
initialization.
 A cla ss’s con s tr u ct or is a u t oma t ica lly ca lled by t h e
compiler each time a n object of t h a t class is created.
 A const r u ct or fu n ct ion h a s t h esa m e n a m e a s t h e
class and has no r e t u r n type.
 There is no explicit way to call the constructor.
D E S T R U C TO R S
 The complement of a constructor is the destructor.
 Th is fu n ct ion is a u t oma t ica lly ca lled by t h e
compiler when a n object is destroyed.
 Th e n a m e of a destr u ct or is t h en a m e of i ts
c la s s, preceded by a ~.
 There is explicit way to call the destructor but highly

discouraged.
Example
C O N S T R U C TO R S &
D E S T R U C TO R S
 F or globa l object s, a n object ’s const r u ct or is
ca lled once, when the program first begins execution.
 F or loca l object s, t h econst r u ct or is ca lled each
t im e the declaration statement is executed.
 Local objects are destroyed when they go out of scope.

 Global objects are destroyed when the program ends.

 Example:
C O N S T R U C TO R S &
D E S T R U C TO R S
 Constructors and destructors are typically declared as
public.
 That is why the compiler can call them when a n object
of a class is declared anywhere in the program.
 If the constructor or destructor function is declared as
p r i vat e then no object of t h a t class can be created
outside of t h a t class. W h a t t y p e of e r r o r ?
 Example: private-cons.cpp, private-des.cpp
C O N S T R U C TO R S THAT TAKE
PARAMETERS
 It is possible t o p a ss a r g u m en t s t o a
con st r u ct or function.
 Destructor functions c a n n o t have parameters.
 A constructor function with no parameter is called the
d e f a u l t c o n s t r u c t o r and is supplied by the compiler
a u t oma t ica lly if n o const r u ct or defin ed by t h e
p rogr a m m er.
 The compiler supplied default constructor doe s n o t
i n i t i a l i z e the member variables to any default value;
so they contain garbage value after creation.
 Constructors c a n be o v e r l o a d e d , but
destructors
c a n n o t be ov e r l oa de d .
 A class can have multiple constructors.

OBJECT POINTERS
 It is possible to access a member of a n object via a
pointer to t h a t object.
 Object pointers play a massive role in run-time
polymorphism (will be introduced later).
 When a pointer is used, the arrow operator (->) r at he r
t h a n the dot operator is employed.
 J u s t like pointers to other types, a n object pointer,
when incremented, will point to the next object of its
type.
 Example:
IN-LINE FUNCTIONS
 Functions t h a t are not actually called but, rather, are
expanded in line, a t the point of each call.
 Advantage

 Have no overhead associated with the function call


and r e t ur n mechanism.
 Can be executed much faster t h a n normal functions.

 Safer t h a n parameterized macros. Why ?


 Disadvantage

 If t h ey a r et oo la r ge a n d ca lled t oo often , t h e
program grows larger.
IN-LINE FUNCTIONS
i n l i n e int even(int  The i n l i n e specifier is a
x) request, not a command, to
{ the compiler.
re tur n !(x%2);  Some compilers will not in-

} line a function if it contains


int main()
 A st ati c variable
{
 A loop, s w i t c h or got o
 A retu rn statement
if(even(10)) cout << “10 is
even\n”;  If the function is re cu r si ve
// b e c o m e s if(!(10%2))

if(even(11)) cout << “11 is


even\n”;
// b e c o m e s if(!(11%2))

re tur n 0;
}
AUTOMATIC IN-LINING
 Defining a member function inside the class
declaration causes the function to automatically
become a n in-line function.
 In this case, the i n l i n e keyword is no longer
necessary.
 However, it is not a n error to use it in this situation.
 Restrictions
 Same as normal in-line functions.
AUTOMATIC IN-LINING
// A u t o ma t ic in-lining // M anual in-lining
class myclass class myclass
{ {
int a; int a;
public: public:
m myclass(int
yclas n); void
s(int set_a(int n); int
n) { a get_a();
= };
n; }
i n l i n e void
void set_a(int n) { a = n; } myclass::set_a(int
int get_a() { r e tu r n a; } n)
}; {
a = n;
A CLOSER LOOK
AT CLASSES
ASSIGNING O B J E C T S
 One object can be assigned to another provided
t h a t both objects are of the same type.
 It is not sufficient t h a t the types just be
physically similar – their type names m us t be the
same.
 By default, when one object is assigned to
another, a bitwise copy of all the da t a members is
made. Including compound da t a structures like
arrays.
 Creates problem when member variables point to
dynamically allocated memory and destructors
are used to free t h a t memory.
 Solution: Copy c on s t r u c t or (to be discussed
later)
 Example:
PA S S I N G O B J E C T S TO
FUN CTI ON S
 Objects can be passed to functions as arguments
in just the same way t h a t other types of da t a
are passed.
 By default all objects are passed by value to a

function.
 Address of a n object can be sent to a function to

implement call by reference.


 Examples:
PA S S I N G O B J E C T S TO
FUN CTI ON S
 In call by reference, as no new objects are formed,
constructors and destructors are not called.
 But in call value, while making a copy, constructors are

not called for the copy but destructors are called.


 Can this cause any problem in any case?

 Yes. Solution: Copy c on s tr uc t or (discussed later)

 Example:
R E T U R N I N G O B J E C T S FROM
FUN CTI ON S
 The function mus t be declared as returning a class
type.
 When a n object is returned by a function, a temporary

object (invisible to us) is automatically created which


holds the return value.
 While making a copy, constructors are not called for

the copy but destructors are called


 After the value has been returned, this object is

destroyed.
 The destruction of this temporary object might cause

unexpected side effects in some situations.


 Solution: Copy c on s t ru c to r (to be discussed later)

 Example:
FRIEND FUNCTIONS
 A friend function is not a member of a class but still has
access to its private elements.
 A friend function can be

 A global function not related to any particular class


 A member function of another class
 Inside the class declaration for which it will be a friend, its
prototype is included, prefaced with the keyword friend.
 Why friend functions ?
 Operator overloading
 Certain types of I/O operations
 Permitting one function to have access to the
members
private of two or more different classes
FRIEND FUNCTIONS
class MyClass // friend keyword not used
{ void ff1(MyClass obj)
int a; // private member {
public: cout << obj.a << endl;
MyClass(int a1) { // c a n a c c e s s p ri vate
a = a1; m e m b e r ‘a’ directly
} MyClass obj2(100);
friend void cout << obj2.a << endl;
ff1(MyClass obj); }
}; void main()
{
MyClass
o1(10); ff1(o1);
}
FRIEND FUNCTIONS
 A friend function is not a member of the class for
which it is a friend.
 MyClass obj(10), obj2(20);
 obj.ff1(obj2); // wrong, compiler error
 Friend functions need to access the members (private,

public or protected) of a class through a n object of t h a t


class. The object can be declared within or passed to
the friend function.
 A member function can directly access class members.

 A function can be a member of one class and a friend of

another.
 E x a m p l e : friend1.cpp, friend2.cpp, friend3.cpp
FRIEND FUNCTIONS
class YourClass; // a fo rw ar d f rien d i nt c o m p a re
d e c la r a t io n (MyClass obj1, YourClass
class MyClass { obj2);
int a; // private member };
public: void main() {
MyClass(int a1) { a = MyClass o1(10); YourClass
a1; } o2(5);
f r ie nd i n t c o m p a re int n = compare(o1, o2); //
(MyClass obj1, YourClass n=5
obj2); }
};
class YourClass { int compare (MyClass
int a; // private member obj1, YourClass obj2) {
public: r e tu r n (obj1.a – obj2.a);
YourClass(int a1) { a }
= a1; }
FRIEND FUNCTIONS
class YourClass; // a fo rw ar d class YourClass {
d e c la r a t io n int a; // private member
class MyClass { public:
int a; // private member YourClass(int a1) { a
public: = a1; }
MyClass(int a1) { a = a1; } friend int MyClass::compare
int compare (YourClass obj) (YourClass obj);
{ };
r e tu r n (a – obj.a) void main() {
} MyClass o1(10); Yourclass
o2(5);
};
int n = o1.compare(o2); // n
=5
}
Operator Overloading
The mechanism of giving a different meaning to an operator is
known as operator overloading.
Operator overloading is done by using a special member function
called as “operator” function.

Syntax of operator function:

return_type classname:: operator op(arguments)


{
Block of Statements;
}
op means the operator that is to be overloaded.
I. Unary Operator Overloading
II. Binary Operator Overloading

Example:
CONVERSION FUNCTION
 Used to convert a n object of one type into a n
object of another type.
 A conversion function automatically converts a n

object into a value t h a t is compatible with the


type of the expression in which the object is
used.
 General form: operator type() {return value;}

 type is the target type and value is the value of

the object after conversion.


 No parameter can be specified.

 Must be a member of the class for which it

performs the conversion.


 Examples :
CONVERSION FUNCTION
#include<iostream> int main()
using namespace std; {
coord o1(2, 3),
class coord o2(4, 3); int i;
{
int x, y; i = o1;
public:
coord(int i, int j){ // automatically converts to
x = i; y = j; } integer cout << i << ‘\n’;
operator int() {
return x*y;
} i = 100 + o2;
}; // automatically converts to
integer cout << i << ‘\n’;
ret urn 0;
}
CONVERSION FUNCTION

52
STATIC C L A S S MEMBERS
 A class member can be declared as s t a t i c
 Only one copy of a s t a t i c variable exists – no

m a t t e r how many objects of the class are created


 All objects share the same variable
 It can be private, protected or public

 A s t a t i c member variable exists before any object

of its class is created


 In essence, a s t a t i c class member is a global

variable t h a t simply has its scope restricted to


the class in which it is declared
STATIC C L A S S MEMBERS
 When we declare a s t a t i c da t a member within a
class, we are not defining it
 Instead, we m us t provide a definition for it

elsewhere, outside the class


 To do this, we re-declare the s t a t i c variable,

using the scope resolution operator to identify


which class it belongs to
 All s t a t i c member variables are initialized to 0

by default
STATIC C L A S S MEMBERS
 The principal reason s t a t i c member variables are
su pport ed by C++ is t o a void t h e n eed for
globa l variables
 Member functions can also be s t a t i c
 Can access only other s t a t i c members of its class
directly
 Need t o a ccess n on -st a t i c m ember s
t h r ough a n object of the class
 Does not have a t h i s pointer
 Cannot be declared as v i r t u a l , co ns t or v o l a t i l e
 s t a t i c member functions can be accessed through a n
object of the class or can be accessed independent of
a n y object , via t h e cla ss n a m e a n d t h e scope
resolution operator
 Usual access rules apply for all s t a t i c members
 Example :
STATIC C L A S S MEMBERS
class myclass { void main ( )
s t a t ic int { myclass ob1,
x; public: ob2;
s t a t ic int cout << ob1.getX() << endl; // 1
y; ob2.setX(5);
int getX() { r e t u r n cout << ob1.getX() << endl; // 5
x; } void setX(int x) { cout << ob1.y << endl; // 2
myclass::x = x; myclass::y = 10;
} cout << ob2.y << endl; // 10
}; // myclass::x = 100;
i nt myclass::x = // will produce compiler error
1; i n t myclass::y }
= 2;
C O N S T MEMBER FUNCTIONS
AND
M U TA B L E
 When a class member is declared as const it can’t

modify the object t h a t invokes it.


 A const object can’t invoke a non-const member

function.
 But a const member function can be called

by either const or non-const objects.


 If you want a const member function to modify

one or more member of a class but you don’t want


the function to be able to modify any of its other
members, you can do this using mutable.
 mutable members can modified by a const

member function.
 Examples:
ARRAYS,
POINTERS
AND
REFE RENCES
A R R AYS OF O B J E C T S
Arrays of objects of class can be declared just like
other variables.
 class A{ … };

A ob[4];
 ob[0].f1(); // l e t f1 i s p u b l i c i n A
 ob[3].x = 3; // l e t x is public in A
 In this example, all the objects of the array are

initialized using the default constructor of A.


 If A does not have a default constructor, then the

above array declaration statement will produce


compiler error.
A R R AYS OF O B J E C T S
 If a class type includes a constructor, a n array of
objects can be initialized
 In it ia lizin g a r r a y elem ent s wit h t h e
const r u ct or taking a n integer argument
c l a s s A{ public: i n t a; A( i nt n) { a = n; } };
 A ob[2] = { A(-1), A(-2) };
 A ob2[2][2] = { A(-1), A(-2), A(-3), A(-4) };
 In t h is ca se, t h efollowin g short h a n d form
ca n also be used
 A ob[2] = { -1, -2 };
A R R AYS OF O B J E C T S
If a const r u ct or t a kes t wo or m ore
a r gu m ent s, then only the longer form can be
used.
c l a s s A{ public: i n t a, b; A(i nt n, i n t m ) { a =
n; b = m; } };
 A ob[2] = { A(1, 2), A(3, 4) };
 Ao b2[2][2] = { A(1, 1), A(2, 2), A(3,
3), A(4, 4) };
A R R AYS OF O B J E C T S
• We can also mix no argument, one argument and
multi-argument constructor calls in a single
array declaration.

class A
{
public:
A() { … } // m u st b e p r esen t fo r t h i s
e x a m p l e t o be c o m p i l e d
A( i n t n) { … }
A( i n t n, i n t m ) { … }
};
– A ob[3] = { A(), A(1),A(2, 3) };
U SI NG P O I N T E R S TO
OBJECTS
 We can take the address of objects using the
address operator (&) and store it in object
pointers.
 A ob; A *p = &ob;
 We have to use the arrow (->) operator instead of
the dot (.) operator while accessing a member
through a n object pointer.
 p->f1(); // l e t f1 i s p u b l i c i n A
 Pointer arithmetic using a n object pointer is the

same as it is for any other da t a type.


 When incremented, it points to the next object.
 When decremented, it points to the previous
object.
TH IS P O I N T E R
 A special pointer in C++ t h a t points to the object
t h a t generates the call to the method
 Let,

 c l a s s A{ public: v o i d f1() { … } };

 A ob; ob.f1();
 The compiler automatically adds a parameter
whose type is “pointer to a n object of the class” in
every non-static member function of the class.
 It also automatically calls the member function
with the address of the object through which the
function is invoked.
 So the above example works as follows –

 c l a s s A{ public: v o i d f1( A *this ) { … } };

 A ob; ob.f1( &ob );


TH IS P O I N T E R
 It is through this pointer t h a t every non-static
member function knows which object’s members
should be used.

class A
{
i n t x;
public:
v
oid

f1()
{
x
thi s P O I N T E R
 this pointer is generally used to access member
variables t h a t have been hidden by local
variables having the same name inside a member
function.
class A{ void f1() {
int x; int x = 0;
cout << x; // p r i n t s
public: v a l u e of l o c a l ‘x’
A(i cout <<
nt x) p r i nt ht sis->x;v a l u//e of
m e m b e r ‘x’
{ }
x = x; // onl y copies
l o c a l ‘x’ t o itself; }
the m e m b e r ‘x’ ;
}r e m a i n s
U SI NG new A N D delete
 C++ introduces two operators for dynamically
allocating and deallocating memory :
 p_var = new type

 new returns a pointer to dynamically allocated


memory t h a t is sufficient to hold a dat a obect
of type type
 de l e t e p _ v a r

 releases the memory previously allocated by


new
 Memory allocated by new m us t be released using
delete
 The lifetime of a n object is directly under our
control and is unrelated to the block structure of
the program
U SI NG new A N D delete
 In ca se of in su fficient m emory, n ew ca n
r epor t failure in two ways
 By returning a null pointer
 By generating a n exception
 The r eact ion of n ew in t h is ca se var ies
fr om compiler to compiler
U SI NG new A N D delete
 Advantages
 No n eed t o u se si z eof opera t or wh ile
u sin g new.
 New a u t oma t ica lly r etu r n s a poin t er
of t h e specified type.
 In ca se of object s, n ew ca lls
dyna m ica lly allocates the object and call its
constructor
 In case of objects, delete calls the destructor of
the object being released
U SI NG new A N D delete
 Dynamically allocated objects can be given initial
values.
 i n t *p = n e w int;
 Dyn a m ica lly alloca tes m emory to st ore a n in t eger
va lue which contains garbage value.
 i n t *p = n e w int(10);
Dynamically allocates memory to store a n integer value and
initializes t h a t memory to 10.
 N ote th e u se of parenth esis ( ) w h ile
supplying initial values.
U SI NG new A N D delete
 c l a s s A{ i n t x; public: A( i n t n ) { x = n; } };
 A *p = n e w A(10);
 Dynamically allocates memory to store a A object and calls
the constructor A(int n) for this object which initializes x to
10.
 A *p = n e w A;
 It will produce c o mpi l e r error because in this example
class A does not have a default constructor.
U SI NG new A N D delete
 We can also create dynamically allocated arrays
using new.
 But deleting a dynamically allocated array needs
a slight change in the use of delete.
 I t i s n o t pos si bl e t o i n i t i a l i z e a n a r r a y t h a t
is dynamically allocated.
 i n t *a= n e w int[10];
 Creates a n a rray of 10 integers
 All integers contain garbage values

 Note the use of square brackets [ ]

 d e l e t e [ ] a;
 Delete the entire arra y pointed by a
 Note the use of square brackets [ ]
U SI NG new A N D delete
 It is not possible to initialize a n array t h a t is
dynamically allocated, in order to create a n array
of objects of a class, the class m us t have a
default constructor.
class A { class A {
int x; int x;
public:
public: A() { x =
A(i 0; }
nt n) A(int n)
{x = {x =
n; } } n; } };
; delete
A *array[ ] array;
= new A[10]; //
n o error
A // u s e array
U SI NG new A N D delete
 A * a r r a y = n e w A[10];
 The default constructor is called for all the
objects.
 d e l e t e [ ] ar r ay ;

 Destructor is called for all the objects


present in the array.
RE FERE N C ES
 A reference is a n implicit pointer
 Acts like another name for a variable

 Can be used in three ways

A reference can be passed to a function


A reference can be returned by a function
 An independent reference can be created
 Referen ce var ia bles a r edecla r ed u sin g t h e&
symbol
 void f(int &n);
 Unlike pointers, once a reference becomes
associated with a variable, it cannot refer to
other variables
RE FERE N C ES
 U s i n g po i n t e r -  U s i n g re f e re n c e -
void f(int *n) { void f(int &n) {
*n = 100; n = 100;
} }
void main() { void main() {
int i = 0; int i = 0;
f(&i); f(i);
cout << i; // cout << i; //
100 100
} }
RE FERE N C ES
 A r eference par a m e ter fu lly a u t oma t es t h e
ca ll- by-reference parameter passing mechanism

 No need to use the address operator (&) while


calling a function taking reference parameter

 Inside a function t h a t takes a reference


parameter, the passed variable can be
accessed without using the indirection
operator (*)
RE FERE N C ES
 Ad van t age s
 The address is automatically passed

 Reduces use of ‘&’ and ‘*’

 Wh en object s a r epassed t o fun ct ions


u sin g references, no copy is made

 Hencedestr u ct ors a r en otca lled wh en t h e


functions ends
E lim in a t es t h et r oubles a ssocia t ed wit h
multiple destructor calls for the same object
PA S S I N G REFERENCES TO
OBJECTS
 We can pass objects to functions using references

 No copy is made, destructor is not called when


the function ends

 As reference is not a pointer, we use the dot


operator (.) to access members through a n object
reference
PA S S I N G REFERENCES TO
OBJECTS
class myclass { void main()
int x; { myclass
public: obj;
myclass() cout << obj.getx() << endl;
{ f(obj);
x = 0; cout << obj.getx() << endl;
cout << }
“Constr
ucting\n Output:
”; Con str u cting
} 0
~myclass() { 500
cout << Destructing
“Destruc
ting\n”;
}
void setx(int n) { x = n; }
int getx() { r et u r n x; }
RETURNING
RE FERE N C ES
 A function can r et urn a reference
 Allows a functions to be used on the left side of

a n assignment statement
 Bu t , t h eobject or var ia ble wh ose r eference is
returned m us t not go out of scope
 So, we should not r et urn the reference of a local

variable
 For the same reason, it is not a good practice
to re t ur n the pointer (address) of a local
variable from a function
RETURNING
RE FERE N C ES
int x; // global variable Output:
int &f() 1
{ r e tu r n 100
x; 2
} So, here f() can be used to both
void main() { set the value of x an d read
the value of x
x = 1;
Example: From Book(151 –
cout << x << endl; 153)
f() = 100;
cout << x << endl;
x = 2;
cout << f() << endl;
}
IN D EP EN D ENT
REFERENCES
 Simply another name for another variable
 Must be initialized when it is declared

 i nt &ref; / / compiler error


 i nt x = 5; i n t &ref = x; / / ok
 ref = 100;
c o u t << x; / / prints “100”

 An independent reference can refer to a constant

 i nt &ref=10; / / compile error


 c o n s t i nt &ref = 10;
RESTRICTIONS
 We c a n n o t re f e re n c e a n o t h e r re f e re n c e
 Doing so just becomes a reference of the
original variable
 We c a n n o t obt a i n t h e a d d re s s of a re f e re n c e

 Doing so returns the address of the original


variable
 Memory allocated for references are hidden
from the programmer by the compiler
 We c a n n o t c re a t e arrays of re f e re n c e s

 We c a n n o t re f e re n c e a bit-field

 R e f e re n c e s m u s t b e i niti al i ze d u n l e s s t h e y
a re m e m b e r s of a class, are re t u r n values, or
are f u n c t i o n p a r a m e t e r s
FUNCTION OVERLOADING
OBJ E CTIVES
 Overloading Constructor Functions
 Creating and Using a Copy Constructor

 The ov erl oa d Anachronism (not in

syllabus)
 Using Default Arguments

 Overloading and Ambiguity

 Finding the address of a n overloaded

function
OVERLOADING
CONSTRUCTOR FUNCTIONS
 It is possible to overload constructors, but
destructors cannot be overloaded.
 Three main reasons to overload a
constructor function
 To gain flexibility
 To support arrays
 To create copy constructors

 There mu st be a constructor function for


each way t h a t a n object of a class will
be created, otherwise compile-time
error occurs.
OVERLOADING
CONSTRUCTOR FUNCTIONS
(CONTD.)
 Let, we w a nt to write
 MyClass ob1, ob2(10);
 Then MyClass should have the following two constructors (it may
have more)
 MyClass ( ) { … }
 MyClass ( int n ) { … }
 Whenever we write a constructor in a class, the compiler does not
supply the default no argument constructor automatically.
 No argument constructor is also necessary for declaring arrays of
objects without any initialization.
 MyClass array1[5]; // uses MyClass () { … } for each element
 But with the help of a n overloaded constructor, we can also
initialize the elements of a n array while declaring it.
 MyClass array2[3] = {1, 2, 3} // uses MyClass ( int n ) { … } for
element
each
OVERLOADING
CONSTRUCTOR FUNCTIONS
(CONTD.)

 Overloading constructor functions also allows the


programmer to select the most convenient method to
create objects.
 Date d1(22, 9, 2007); // uses Date( int d, int m, int y )
 Date d2(“22-Sep-2007”); // uses Date( char* str )
 Another reason to overload a constructor function is to
support dynamic arrays of objects created using
“new”.
 As dynamic arrays of objects cannot be initialized, the

class m u st have a no argument constructor to avoid


compiler error while creating dynamic arrays using
“new”.
CREATING AND USING A
COPY CONSTRUCTOR
 By default when a assign a n object to another object or
initialize a new object by a n existing object, a bitwise copy
is performed.
 This cause problems when the objects contain pointer to
dynamically allocated memory an d destructors are used to
free t h a t memory.
 It causes the same memory to be released multiple times
t h a t causes the program to crash.
 Copy constructors are used to solve this problem while we
perform object initialization with another object of the
same class.
 MyClass ob1;
 MyClass ob2 = ob1; // uses copy constructor
 Copy constructors do not affect assignment operations.
 MyClass ob1, ob2;
 ob2 = ob1; // does not use copy constructor
CREATING AND USING A
COPY CONSTRUCTOR
(CONTD.)
 If we do not write our own copy
constructor, then the compiler supplies
a copy constructor t h a t simply
performs bitwise copy.
 We can write our own copy constructor to
dictate precisely how members of two
objects should be copied.
 The most common form of copy
constructor is
 classname (const classname &obj)
 // body of constructor
{

}
CREATING AND USING A
COPY CONSTRUCTOR
(CONTD.)

 Object initialization can occur in three ways


 When a n object is used to initialize another in a declaration
statement
 MyClass y;
 MyClass x = y;

 When a n object is passed as a par am eter to a function


 func1(y); // calls “void func1( MyClass obj )”
 When a temporary object is created for use as a r e t u r n value
by a function
 y = func2(); // gets the object returned from “MyClass func2()”
 See the examples from the book and the supplied
codes to have a better understanding of the activities
and usefulness of copy constructors.
 Example: copy-cons.cpp
USING DEFAULT ARGUMENTS

 It is related to function overloading.


 Essentially a shorthand form of function overloading
 It allows to give a parameter a default value when no
corresponding argument is specified when the
function is called.
 void f1(int a = 0, int b = 0) { … }
 It can now be called in three different ways.
 f1(); // inside f1() ‘a’ is ‘0’ a nd b is ‘0’
 f1(10); // inside f1() ‘a’ is ‘10’ a nd b is ‘0’

 f1(10, 99); // inside f1() ‘a’ is ‘10’ a nd b is ‘99’

 We can see t h a t we cannot give ‘b’ a new (non-default) value


without specifying a new value for ‘a’.
 So while specifying non-default values, we have to s ta r t
the
fromleftmost parameter and move to the right one by one.
USING DEFAULT ARGUMENTS
(CONTD.)

 Default arguments m us t be specified only once: either


in the function’s prototype or in its definition.
 All default parameters m us t be to the right of any
parameters t h a t don’t have defaults.
 void f2(int a, int b = 0); // no problem
 void f3(int a, int b = 0, int c = 5); // no problem
 void f4(int a = 1, int b); // compiler error
 So, once you begin to define default parameters, you
cannot specify any parameters t h a t have no defaults.
 Default arguments m us t be constants or global
variables. They cannot be local variables or
other parameters.
USING DEFAULT ARGUMENTS
(CONTD.)

 Relation between default arguments and


function overloading.
 void f1( int a = 0, int b = 0 ) { … }
 It acts as the same way as the following overloaded
functions –
 void f2( ) { int a = 0, b = 0; … }
 void f2( int a ) { int b = 0; … }

 void f2( int a, int b ) { … }

 Constructor functions can also have default


arguments.
USING DEFAULT ARGUMENTS
(CONTD.)

 It is possible to create copy constructors t h a t take


additional arguments, as long as the additional
arguments have default values.
 MyClass( const MyClass &obj, int x = 0 ) { … }
 This flexibility allows us to create copy constructors
t h a t have other uses.
 See the examples from the book to learn more about

the uses of default arguments.


OVERLOADING AND AMBIGUITY
 Due to automatic type conversion rules.
 Example 1:

 void f1( float f ) { … }


 void f1( double d ) { … }
float x = 10.09;
 double y = 10.09;
 f1(x); // unambiguous – use f1(float)
 f1(y); // unambiguous – use f1(double)
 f1(10); // ambiguous, compiler error
 Because integer ‘10’ can be promoted to both “float” and
“double”.
OVERLOADING AND
AMBIGUITY (CONTD.)
 Due to the use of reference parameters.
 Example 2:


b ) {… }
void f2( int a, int


void f2(int a, int &b ) { … }
 int x = 1, y = 2;
 f2(x, y); // ambiguous, compiler error
OVERLOADING AND
AMBIGUITY (CONTD.)
 Due to the use of default arguments.
 Example 3:

 void f3( int a ) { … }



void f3(int a, int b=0 ) {… }
 f3(10, 20); // unambiguous – calls f3(int, int)
 f3(10); // ambiguous, compiler error
FINDING THE ADDRESS OF
AN OVERLOADED FUNCTION
 Example:
 void space( int a ) { … }
 void space( int a, char c ) { … }

 void (*fp1)(int);

 void (*fp2)(int, char);

 fp1 = space; // gets address of space(int)


 fp2 = space; // gets address of space(int,
char)
 So, it is the declaration of the pointer t h a t
determines which function’s address is
assigned.
INHERITANCE
OBJ E CTIVES
 Base class access control
 Using p ro t e c t e d members

 Visibility of base class members in derived class

 Constructors, destructors, and inheritance

 Multiple inheritance

 Virtual base classes


BASE CLASS ACCESS CONTROL
 class derived-class-name : acces s base-
class-name
{ … };
 Here access is one of three keywords

 public
 private
 protected
 Use of access is optional
 It is private by default if the derived class is
a
c l as s
 It is public by default if the derived class is a
USING PROTECTED MEMBERS
 Cannot be directly accessed by non-related
classes and functions
 But can be directly accessed by the derived

classes
 Can also be used with structures
VISIBILITY OF BASE CLASS
MEMBERS IN DERIVED CLASS
When a class (derived) inherits from another (base) class, the visibility
of the members of the base class in the derived class is as follows.

Member visibility in derived class


Type of Inheritance

Member access Private Protected


specifier in Public
base class
Private Not Inherited Not Inherited Not Inherited
Protected Private Protected Protected
Public Private Protected Public
CONSTRUCTORS,
DESTRUCTORS, AND
INHERITANCE
 Both base class and derived class can have
constructors and destructors.
 Constructor functions are executed in the
order of derivation.
 Destructor functions are executed in the
reverse order of derivation.
 While working with a n object of a derived
class, the base class constructor and
destructor are always executed no
mat t er how the inheritance was done
(private, protected or public).
CONSTRUCTORS,
DESTRUCTORS, AND
INHERITANCE (CONTD.)
 class base {  void main()
 public:  { derived
 base() {  obj;
 cout << }
 “Constr  Ou t pu t :
 ucting  Constructing base class
 Constructing derived class
 base  Destructing derived class
 class\n  Destructing base class
 ”;
 }
 ~base() {
 cout <<
 “Destru
cout << “Constructing derived
class\n”;
cting
 } base
 ~derived()
class\n
 { cout
”; << “Destructing derived
class\n”;
}
 }
};
 };
class derived : public base {
CONSTRUCTORS,
DESTRUCTORS, AND
INHERITANCE (CONTD.)
 If a base class constructor takes parameters then
it is the responsibility of the derived class
constructor(s) to collect t hem and pass them to
the base class constructor using the following
syntax -
 derived-constructor(arg-list) : base(arg-list) { … }
 Here “base” is the name of the base class
 It is permissible for both the derived class and
the base class to use the same argument.
 It is also possible for the derived class to ignore

all arguments and just pass them along to


the base class.
CONSTRUCTORS,
DESTRUCTORS, AND
INHERITANCE (CONTD.)
 class MyBase {  void main() {
 public:  MyDerived o1; // x = 0, y = 0
 int x;  MyDerived o2(5); // x = 5, y = 0
 MyBase(int  MyDerived o3(6, 7); // x = 6, y = 7
 m) { x = m; }  }
 };
 class MyDerived : public MyBase {
 public:
 As “MyBase” does not have a default
(no argument) constructor, every
 int y; constructor of “MyDerived” must
 MyDerived() : MyBase(0) { y = 0; } pass the parameters required by the
 MyDerived(int a) : MyBase(a) “MyBase” constructor.
 {
 y = 0;
 }
 MyDerived(int a, int b) :
 MyBase(a)
 {
 y = b;
}
};
MULTIPLE INHERITANCE

 A derived class can inherit more t h a n one base


class in two ways.
 Option-1: By a chain of inheritance
 b1 -> d1 -> dd1 -> ddd1 -> …
 Here b1 is a n indirect base class of both dd1 a n d ddd1

 Constructors are executed in the order of inheritance

 Destructors are executed in the reverse order

 Option-2: By directly inheriting more t h a n one base


class
 class d1 : access b1, access b2, …, access bN { … }
 Constructors are executed in the order, left to right, t h a t the

base classes are specified


 Destructors are executed in the reverse order
MULTIPLE INHERITANCE (CONTD.)

b1

b1 b2 b3
d1

dd1
d1

ddd1

Option - 1 Option - 2
VIRTUAL BASE CLASSES

 Consider the

D
p
situation shown. Base Base a
rt

 Two copies of

Base ,
B
D1 D2 U
are included in E

T
D3.
 This causes

ambiguity when a D3
member of Base is
directly used by D3.
VIRTUAL BASE CLASSES (CONTD.)
 class D3 : public D1,
 class Base { public D2 {
 public: // contains two copies of

 int i; ‘i’
 };  };
 class D1 : public Base {  void

 public:

main() {
 int j; D3 obj;
 };  obj.i = 10; //
 class D2 : public Base {  ambiguous, compiler
 public: 
error
 int k; obj.j = 20; // no
 problem obj.k =
 };
30; // no problem
obj.D1::i = 100; // no
 } problem

obj.D2::i = 200; //
no problem
VIRTUAL BASE CLASSES (CONTD.)

 class Base {  class D3 : public D1, public D2 {


 public:  // contains only one copy of ‘i’
 int i;  }; // no change in this class

 }; definition
 class D1 : virt ual public Base {  void main()

 public: { D3 obj;

 int j; obj.i = 10; // no
 problem
 }; // activity of D1 not affected

obj.j = 20; // no problem
 class D2 : virt ual public Base {
 obj.k = 30; // no problem
 public:
 int k; obj.D1::i = 100; // no problem,
 overwrites ‘10’
 }; // activity of D2 not affected
obj.D2::i = 200; // no problem,
 }overwrites ‘100’
VIRTUAL FUNCTIONS
OBJ E CTIVES
 Polymorphism in C++
 Pointers to derived classes

 Important point on inheritance

 Introduction to virtual functions

 Virtual destructors

 More about virtual functions

 Final comments

 Applying polymorphism
POLYMORPHISM IN C++
 2 types
 Compile time polymorphism
 Uses static or early binding
 Example: Function a nd operator

overloading
 Run time polymorphism
 Uses dynamic or early
binding
 Example: Virtual functions
POINTERS TO DERIVED CLASSES
 C++ allows base class pointers to point to
derived class objects.
 Let we have –

 class base { … };
 class derived : public base { … };
 Then we can write –
 base *p1; derived d_obj; p1 = &d_obj;
 base *p2 = new derived;
POINTERS TO DERIVED
CLASSES (CONTD.)
 Using a base class pointer (pointing to a
derived class object) we can access only
those members of the derived object
t h a t w e r e i n h e r i t e d from t h e base.
 It is different from the behavior t h a t J a va
shows.
 We can get Java-like behavior using virtual
functions.
 This is because the b a s e p o i nt e r has
knowledge only of the base class.
 It knows nothing about the members
added by the derived class.
POINTERS TO DERIVED
CLASSES (CONTD.)
 class base {  void main() {
 public:  base b1;
 void show() {  b1.show(); // base
 cout << “base\n”;  derived d1;
 }  d1.show(); // derived
 };  base *pb = &b1;
 class derived : public base {  pb->show(); // base
 public:  pb = &d1;
 void show() {  pb->show(); //
 cout << “derived\n”;
} base
 }  All the function calls here
 }; are statically bound
POINTERS TO DERIVED
CLASSES (CONTD.)
 While it is permissible for a base class pointer
to point to a derived object, the reverse is not
true.
 base b1;
 derived *pd = &b1; // compiler error
 We can perform a d o w n c a s t with the help of
type-casting, but should use it with caution (see
next slide).
POINTERS TO DERIVED
CLASSES (CONTD.)

 Let we have –
 class base { … };
 class derived : public base { … };
 class xyz { … }; // having no relation with “base” or “derived”
 Then if we write –
 base b_obj; base *pb; derived d_obj; pb = &d_obj; // ok
 derived *pd = pb; // compiler error
 derived *pd = (derived *)pb; // ok, valid downcasting
 xyz obj; // ok
 pd = (derived *)&obj; // invalid casting, no compiler error,
but may cause run-time error
 pd = (derived *)&b_obj; // invalid casting, no compiler
error, but may cause run-time error
POINTERS TO DERIVED
CLASSES (CONTD.)

 In fact using type-casting, we can use pointer of


any class to point to a n object of any other class.
 The compiler will not complain.
 During run-time, the address assignment will also
succeed.
 But if we use the pointer to access any member, then it
may cause run-time error.
 J a v a prevents such problems by throwing
“ClassCastException” in case of invalid casting.
POINTERS TO DERIVED
CLASSES (CONTD.)

 Pointer arithmetic is relative to the dat a type


the pointer is declared as pointing to.
 If we point a base pointer to a derived object

and then increment the pointer, it will not


be pointing to the next derived object.
 It will be pointing to (what it thinks is) the

next base object !!!


 B e careful a b o u t this.
IMPORTANT POINT ON
INHERITANCE

In C++, only public inheritance supports the perfect IS-A


relationship.
 In case of private an d protected inheritance, we cannot tre at a
derived class object in the same way as a base class object
 Public members of the base class becomes private or protected in the
derived class a nd hence cannot be accessed directly by others using
derived class objects
 If we use private or protected inheritance, we cannot assign the
address of a derived class object to a base class pointer
directly.
 We can use type-casting, but it makes the program logic and
structure complicated.
 This is one of the reason for which J a v a only supports public
inheritance.
INTRODUCTION TO VIRTUAL
FUNCTIONS
 A virtual function is a member function
t h a t is declared within a base class and
redefined (called o ve r ri d i ng ) by a
derived class.
 It implements the “one interface, multiple
methods” philosophy t h a t underlies
polymorphism.
 The keyword virtual is used to designate
a member function as virtual.
 Supports run-time polymorphism with the
help of base class pointers.
VIRTUAL FUNCTIONS
(CONTD.)
 While redefining a virtual function in a derived
class, the function signature m us t match the
original function present in the base class.
 So, we call it o v e r r i d i n g , not overloading.

 When a virtual function is redefined by a derived


class, the keyword virtual is not needed (but
can be specified if the programmer wants).
 The “virtual”-ity of the member function
continues along the inheritance chain.
 A class t h a t contains a virtual function is
referred to as a p o l y m o r p h i c class .
VIRTUAL FUNCTIONS
(CONTD.)
class base { void main() {
 public:  base b1;
 virtual void show()  b1.show(); // base - (s.b.)
 { cout << “base\n”;  derived d1;
 }  d1.show(); // derived – (s.b.)
 };  base *pb = &b1;
 class derived : p u b lic b a s e {  pb->show(); // base - (d.b.)
 public:
 p b = &d1;
 void show() {  pb->show(); // d e r i v e d
(d.b.)
 cout << “derived\n”;
 } }

 };  Here,
 s.b. = static binding
 d.b. = dynamic binding
VIRTUAL FUNCTIONS
(CONTD.)
class base {
 public:  class d2 : p u b lic b a s e {
 public:
 virtual void show() 

 { cout << “base\n”;  void show() {


 }  cout << “derived-2\n”;
 }; }
 };
 class d1 : p u b lic b a s e {

 public:  void
 main() {
 base *pb; d1 od1; d2
 void show() {
 od2; int n;
 cout << “derived-1\n”;
 }  cin >> n;
 };  if (n % 2) pb = &od1;
 else pb = &od2;
Run-time polymorphism } pb->show(); // g u e s s
VIRTUAL DESTRUCTORS
 Constructors cannot be virtual, but destructors
can be virtual.
 It ensures t h a t the derived class destructor is

called when a base class pointer is used


while deleting a dynamically created
derived class object.
VIRTUAL DESTRUCTORS (CONTD.)

 class base {  void main() {


 public:  base *p = new derived;
 ~base() {  delete p;
 cout <<  }

 “destru  Output:
 cting  destructing base
 base\n
 ”;
 }
 };
 class derived : public base {
public:
~derived() {
Using
cout << “destructing non-virtual destructor
derived\n”;
}
VIRTUAL DESTRUCTORS (CONTD.)

 class base {  void main() {


 public:  base *p = new derived;
 virtual  delete p;
 ~base() {  }
 cout <<
  Output:
 “destru  destructing derived
 cting  destructing base
 base\n

”;

}

};
class derived : public base {
public:
~derived() { Using virtual destructor
cout << “destructing
derived\n”;
MORE ABOUT VIRTUAL FUNCTIONS
 If we want to omit the body of a virtual
function in a base class, we can use pure
virtual functions.
 virtual ret-type func-name(param-list) = 0;
 It makes a class a n a b s t r a c t class .
 We cannot create any objects of such classes.
 It forces derived classes to override it.
 Otherwise they become abstract too.
MORE ABOUT VIRTUAL
FUNCTIONS (CONTD.)
 Pure virtual function
 Helpsto guarantee t h a t a derived class will
provide its own redefinition.
 We can still create a pointer to a n abstract
class
 Because it is a t the he art of run-time
polymorphism
 When a virtual function is inherited, so is
its virtual nature.
 We can continue to override virtual

functions along the inheritance hierarchy.


FINAL COMMENTS

 Run-time polymorphism is not automatically


activated in C++.
 We have to use virtual functions and base class
pointers to enforce and activate run-time
polymorphism in C++.
 But, in Java, run-time polymorphism is
automatically present as all non-static
m e t h o d s of a class are by default virtual in
nature.
 We just need to use superclass references to point to
subclass objects to achieve run-time polymorphism
in Java.
APPLYING POLYMORPHISM
 Early binding
 Normal functions, overloaded functions
 Nonvirtual member and friend functions
 Resolved a t compile time
 Very efficient
 But lacks flexibility
 Late binding
 Virtual functions accessed via a base class pointer
 Resolved a t run-time
 Quite flexible during run-time
 But ha s run-time overhead; slows down program
execution
LECTURE CONTENTS
 Teach Yourself C++
 Chapter 10 (Full, with exercises)
 Study the examples from the book carefully
MANIPULATING
STRINGS
INTRODUCTION
 A string is a sequence of character.

 We have used null terminated <char> arrays (C-


strings or C-style strings) to store and
manipulate strings.

 ANSI C++ provides a class called string.

 We m us t include <string> in our program.


AVAILABLE OPERATIONS
 Creating string objects.
 Reading string objects from keyboard.

 Displaying string objects to the screen.

 Finding a substring from a string.

 Modifying string objects.

 Adding string objects.

 Accessing characters in a string.

 Obtaining the size of string.

 And many more.


COMMONLY USED STRING
CONSTRUCTORS
 String();
 // For creating a n empty string.
 String(const char *str);
 //For creating a string object from a null-terminated
string.
 String(const string &str);
 //For creating a string object from other string
object.
CREATING STRING OBJECTS
 string s1, s3; // Using constructor with no
arguments.
 string // Using one-argument constructor.
s2(“xyz”); // Assigning string objects
 s1 = s2; // Concatenating strings
s3 = “abc” +
s2; // Reading from keyboard (one word)
// Display the content of s2
 cin >> s1; // Reading from keyboard a line of text
 cout << s2;
getline(cin, // s3 = s3 + s1;
s1) // s3 = s3 + “abc”;
MANIPULATING STRING OBJECTS
 string s1(“12345”);
 string s2(“abcde”);

 s1.insert(4, s2); // s1 = 1234abcde5

 s1.erase(4, 5); // s1 = 12345

 s2.replace(1, 3, s1); // s2 = a12345e


MANIPULATING STRING OBJECTS
 insert()

 erase()

 replace()

 append()
RELATIONAL OPERATIONS
Operator M e an i ng
== Equality
!= Inequality
< Less t h a n
<= Less t h a n or equal
> Greater t h a n
>= Greater t h a n or equal

 string s1(“ABC”); string s2(“XYZ”);


 int x = s1.compare(s2);

 x == 0 if s1 == s2
 x > 0 if s1 > s2
 x < 0 if s1 < s2
STRING CHARACTERISTICS
void display(string &str)
{
cout << “Size = ” << str.size() << endl;
cout << “Length = ” << str.length() << endl;
cout << “Capacity = ” << str.capacity() << endl;
cout << “Max Size = ” << str.max_size() << endl;
cout << “Empty: ” << (str.empty() ? “yes” : “no”)
<< endl;
cout << endl << endl;
}
STRING CHARACTERISTICS
Function Task
size() Number of elements currently
stored
length() Number of elements currently
stored
capacity() Total elements t h a t can be stored
max_size() Maximum size of a string
object t h a t a system can
support
emply() Return t rue or 1 if the string is
empty otherwise returns false or
0
resize() Used to resize a string
object (effects only size and
length)
ACCESSING CHARACTERS IN
STRINGS
Function Task
at() For accessing individual characters
substr() For retrieving a substring
find() For finding a specific substring
find_first_of() For finding the location of first occurrence of the
specific character(s)
find_last_of() For finding the location of first occurrence of the
specific character(s)

[] operator For accessing individual character. Makes the string


object to look like a n array.
COMPARING AND SWAPPING
 There is another overloaded version of compare

 int compare(int start_1, int length_1, string s_2,


int start_2, int length_2)

 string s1, s2;


 int x = s1.compare(0, 2, s2, 2, 2);

 s1.swap(s2)
 Exchanges the content of string s1 and s2

You might also like