C++ Ppts
C++ Ppts
OF C++
OBJECTIVES
Introduction
What is object-oriented programming?
language.
C++ adds support for OOP without
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
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.
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.
keywords
t r u e (any nonzero value) and false (zero).
I N T R O D U C I N G FUNCTION
OVERLOADING
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
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.
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
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-
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
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
destroyed.
The destruction of this temporary object might cause
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
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.
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
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
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
function.
But a const member function can be called
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
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
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 –
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
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 ;
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
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
syllabus)
Using Default Arguments
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
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 (*fp1)(int);
Multiple inheritance
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.
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.)
}; 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
Virtual destructors
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.)
}; 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()
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
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
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)
s1.swap(s2)
Exchanges the content of string s1 and s2