C
C
1
What is C++?
2
Programming Paradigms
• Procedural Programming (functions)
• Modular Programming (namespaces)
• Object Oriented Programming (classes)
• Generic Programming (templates)
3
C++ vs C
Most C programs are also C++ programs.
4
Structure of C++
The code is divided into six major parts:
1. Comment line
2. Header file //#include <iostream>
3. using namespace std; //[option]
4. Class declaration; //[option]
5. int main() //single main definition
{
6. Object creation;
7. Member invoke through objects;
5
“Hello World” in C++
Use the standard namespace Include standard
iostream classes
9
Type Casting
• Two types
– Implicit—also called "Automatic"
• Done FOR you, automatically
17 / 5.5
This expression causes an "implicit type cast" to
take place, casting the 17 17.0
– Explicit type conversion
• Programmer specifies conversion with cast operator
(double)17 / 5.5
Same expression as above, using explicit cast
(double)myInt / myDouble
More typical use; cast operator on variable
1-10
Memory Layout
The address space consists of (at least):
Text: executable program text (not writable)
Static: static data
Heap: dynamically allocated global memory (grows upward)
Stack: local memory for function calls (grows downward)
11
Basic Input / Output in C++
Header files available in C++ for Input – Output operation are:
• iostream: iostream stands for standard input output stream. This
header file contains definitions to objects like cin, cout, cerr etc.
• iomanip: iomanip stands for input output manipulators. The
methods declared in this files are used for manipulating streams.
This file contains definitions of setw, setprecision etc.
• fstream: This header file mainly describes the file stream. This
header file is used to handle the data being read from a file as
input or data being written into the file as output.
• In C++ articles, these two keywords cout and cin are used very
often for taking inputs and printing outputs.
– The extraction operator(>>) is used along with the object cin
for reading inputs.(No literals allowed for cin Must input "to a
variable"
• The insertion operator(<<) insert the value of the variable
12
• Un-buffered standard error stream (cerr): cerr is
the standard error stream which is used to output
the errors. This is also an instance of the ostream
class.
– cerr << "An error occured";
• buffered standard error stream (clog): This is
also an instance of ostream class and used to
display errors but unlike cerr the error is first
inserted into a buffer and is stored in the buffer
until it is not fully filled.
– clog << "An error occured";
13
Operators in C / C++
14
Example 1: Hello World Program
#include <iostream>
int main()
{
cout << "Hello, World!";
return 0;
}
15
If statements
True False
condition
if (condition)
{
S1; S2
S1
}
else
{
S2;
} S3
S3;
16
Boolean conditions
..are built using
• Comparison operators
== equal
!= not equal
< less than
> greater than
<= less than or equal
>= greater than or equal
• Boolean operators
&& and
|| or
! not
17
Examples
Assume we declared the following variables:
int a = 2, b=5, c=10;
18
If example
#include <iostream.h>
void main()
{
int a,b;
cin >> a >> b ;
if (a <=b)
{
cout << “min is “ << a << endl;
}
else
{
cout << “ min is “ << b << endl;
}
cout << “happy now?” << endl;
}
19
While statements
while (condition)
{
S1;
}
S2;
20
While example
//read 100 numbers from the user and output their sum
#include <iostream.h>
void main() {
int i, sum, x;
sum=0;
i=1;
while (i <= 100) {
cin >> x;
sum = sum + x;
i = i+1;
}
cout << “sum is “ << sum << endl;
}
21
Example: Check Prime Number
#include <iostream> for(i = 2; i <= n / 2; ++i)
using namespace std; {
if(n % i == 0)
{
int main() isPrime = false;
{ break;
int n, i; }
bool isPrime = true; }
if (isPrime)
cout << "This is a prime number";
cout << "Enter a positive
else
integer: ";
cout << "This is not a prime
cin >> n; number";
return 0;
22
}
Functions in C/C++
23
Function Declaration
• Function declaration tells compiler about
number of parameters function takes, data-
types of parameters and return type of
function.
24
Difference between Call by Value and Call by
Reference
• The parameters passed to function are called actual parameters
whereas the parameters received by function are called formal
parameters.
25
void swapx(int x, int y); #include <stdio.h>
int main()
void swapx(int*, int*);
{
int a = 10, b = 20; int main()
{
int a = 10, b = 20;
// Pass by Values
swapx(a, b); // Pass reference
swapx(&a, &b);
t = x; t = *x;
x = y; *x = *y;
*y = t;
printf("x=%d y=%d\n", x, y);
} printf("x=%d y=%d\n", *x, *y);
}
Output:x=20 y=10 a=10 b=20 Output:x=20 y=10 a=20 b=10
26
Types of Class Member Functions in C++
• Simple functions
– These are the basic member function, which dont have any special
keyword like static etc as prefix.
return_type functionName(parameter_list)
{
function body;
}
• Static functions
– A function is made static by using static keyword with function name.
These functions work for the class as whole rather than for a particular
object of a class.
– It can be called using the object and the direct member access .
operator. But, its more typical to call a static member function by itself,
using class name and scope resolution :: operator.
– It doesn't have any "this" keyword which is the reason it cannot access
ordinary members. 27
Example static function
class X
{
public:
static void f()
{
// statement must use static variable
}
};
int main()
{
X::f(); // calling member function directly with class name
}
28
• Const functions
– Member functions can never modify the object or its
related data members.
• Inline functions
– All the member functions defined inside the class
definition are by default declared as Inline
• Friend functions
– Friend functions are actually not class member function
29
#include <iostream>
using namespace std; void printWidth( Box box )
class Box {
{ cout << "Width of box : " <<
double width; box.width <<endl;
}
public: int main()
friend void printWidth( Box {
box ); Box box;
void setWidth( double wid ); box.setWidth(10.0);
}; printWidth( box );
return 0;
// Member function definition }
void Box::setWidth( double wid )
{
width = wid;
}
30
Pointers in C++
int i;
int *iPtr; // a pointer to an integer
31
References
A reference is an alias for another variable:
i,ir 10
int i = 10;
int &ir = i; // reference (alias)
ir = ir + 1; // increment i
33
C++ Classes
C++ classes may be instantiated either automatically (on the stack):
35
Constructors and destructors
Include standard iostream
and string classes
#include <iostream>
#include <string>
class myClass {
public:
myClass(void); // default constructor
myClass(const myClass& copy); // copy constructor
... // other constructors
~myClass(void); // destructor
... // other public member functions
private:
...
};
37
Example: A String Class
We would like a String class that protects C-style strings:
• strings are indistinguishable from char pointers
• string updates may cause memory to be corrupted
38
A Simple String.h
Returns a Operator A friend function
reference to overloading prototype
class String
ostream declaration of the
{
friend ostream& operator<<(ostream&, const String class
String&);
public:
String(void); Operator
// default constructor
~String(void); // destructor overloading of =
inline String(const String& copy); // copy constructor
String(const char*s); // char* constructor
String& operator=(const String&); // assignment
The default constructor for a class is called when a new instance is declared
without any initialization parameters:
String anEmptyString; // call String::String()
String stringVector[10]; // call it ten times!
40
Destructors
The String destructor must explicitly free any memory
allocated by that object.
String::~String (void) free memory
{
delete [] _s;
}
43
Polymorphism Definition
Polymorphous:
– Having, or assuming, various forms, characters, or
styles. Term used in several different ways in
computer science
Prof.A.KANNAMMAL,JCET 44
Types of Polymorphism
• Two types of Polymorphism are available in C++ object
oriented programming i.e. compile time and run time
polymorphism. Also, known as early binding and late binding
respectively.
• Compiler time polymorphism features in C++ language are
function overloading, constructor and operator overloading
etc. and run time polymorphism is function overriding in
inheritance relationship.
Prof.A.KANNAMMAL,JCET 45
C++ Overloading (Function and Operator)
46
C++ Operators Overloading
+ - * / % ^ & |
+= -= /= %= ^= &= |= *=
48
Operator that cannot be overloaded are as
follows:
• Scope operator (::)
• Sizeof
• member selector(.)
• member pointer selector(*)
• ternary operator(?:)
49
Syntax of Operator Overloading
return_type class_name : : operator op(argument_list)
{
// body of the function.
}
51
Forms of Polymorphism
• overloading – same alone same
• overriding –all element should same
• Function Overloading (achieved at compile time)
• It provides multiple definitions of the function by changing signature
i.e changing number of parameters, change datatype of parameters,
return type doesn’t play anyrole.
• Function Overriding (achieved at run time)
• It is the redefinition of base class function in its derived class with
same signature i.e return type and parameters.
• It can only be done in derived class.
Prof.A.KANNAMMAL,JCET 52
Polymorphic Variables
• Should not be confused with coercion (casting) – one type is converted into another
for operation
Prof.A.KANNAMMAL,JCET 54
Abstract Class
• Abstract Class is a class which contains atleast
one Pure Virtual function in it. Abstract classes
are used to provide an Interface for its sub
classes. Classes inheriting an Abstract Class
must provide definition to the pure virtual
function, otherwise they will also become
abstract class.
55
Characteristics of Abstract Class
57
/Abstract base class
class Base
{
public:
virtual void show() = 0; // Pure Virtual Function
};
int main()
{
Base obj; //Compile Time Error
Base *b;
Derived d;
b = &d;
b->show();
}
58
Inheritance
59
Concept of Inheritance (continue)
• Why Inheritance?
- code reusability (save time and money)
- Increasing program reliability
- Better problem-solving and program design
- Supporting polymorphism
Define a Class Hierarchy
• Syntax:
class DerivedClassName : access-level BaseClassName
where
– access-level specifies the type of derivation
• private by default, or
• public
• Any class can serve as a base class
– Thus a derived class can also be a base class
61
Access Rights of Derived Classes
Type of Inheritance
private - - -
protected private protected protected
public private protected public
62
Inheritance Concept
• Augmenting the original class
Polygon Point
Prof.A.KANNAMMAL,JCET 64
Prof.A.KANNAMMAL,JCET 65
Base and Derived Classes
Student GraduateStudent
UndergraduateStudent
Shape Circle
Triangle
Rectangle
Loan CarLoan
HomeImprovementLoan
MortgageLoan
Employee FacultyMember
StaffMember
Account CheckingAccount
SavingsAccount
Prof.A.KANNAMMAL,JCET 66
Inheritance
• One object type is defined as being a special
version of some other object type.
– a specialization.
• The more general class is called:
– base class, super class, parent class.
• The more specific class is called:
– derived class, subclass, child class.
Prof.A.KANNAMMAL,JCET 67
Composition vs. Inheritance
• "is a" relationship
– Inheritance
• "has a" relationship
– Composition - class has an object from another class as a data
member
Prof.A.KANNAMMAL,JCET 68
Advantages of inheritance
Prof.A.KANNAMMAL,JCET 70
Forms of Inheritance
• Derived class inherits from base class
• Public Inheritance (“is a”)
– Public part of base class remains public
– Protected part of base class remains protected
• Protected Inheritance (“contains a”)
– Public part of base class becomes protected
– Protected part of base class remains protected
• Private Inheritance (“contains a”)
– Public part of base class becomes private
– Protected part of base class becomes private
Prof.A.KANNAMMAL,JCET 71
Concept of Inheritance (continue)
• Conceptual examples
- example 1: circle
r
base class: circle
area = 3.1415*r*r
class Triangle{
protected:
class Triangle : public Polygon{ int numVertices;
public: float *xCoord, float *yCoord;
float area(); public:
void set(float *x, float *y, int nV);
};
float area();
74
};
Multiple Inheritance in C++
75
int main()
#include<iostream>
{
using namespace std; C c;
return 0;
class A
{ }
public:
A() { cout << "A's constructor called" << endl; }
}; Output:
class B
{
B's constructor called
public: A's constructor called
B() { cout << "B's constructor called" << endl; }
C's constructor called
};
class C: public B, public A // Note the order The destructors are called in reverse
{
order of constructors.
public:
C() { cout << "C's constructor called" << endl; }
};
76
77
class derived : public base
Call parent constructor {
and pass in parameter int j;
public:
#include <iostream> derived(int x, int y): base(y){
using namespace std; j=x;
class base
cout << "Constructing derived.\n";
{
}
protected:
int i; ~derived(void) {cout << "Destructing
derived.\n";}
public:
base(int x) void show(void) {cout << i << ", " << j
{
<< endl;}
i=x; };
cout << "Constructing base.\n"; int main(void)
} {
~base(void) {cout << "Destructing derived object(3,4);
base.\n";}
};
object.show();
78
}
Passing and Returning Objects in C++
79
Example for objects as arguments : // Values are initialized for both objects
#include <bits/stdc++.h> E1.a = 50;
using namespace std; E2.a = 100;
class Example {
public: cout << "Initial Values \n";
int a; cout << "Value of object 1: " << E1.a
<< "\n& object 2: " << E2.a
void add(Example E) << "\n\n";
{ // Passing object as an argument
a = a + E.a; E2.add(E1);
} // Changed values after passing
}; cout << "New values \n";
int main() cout << "Value of object 1: " << E1.a
{ << "\n& object 2: " << E2.a
<< "\n\n";
// Create objects return 0;
Example E1, E2; } 80
Array of objects
• #include<iostream.h>
#include<conio.h>
class rec
{
private:
int I;
int b;
public:
rec(int a,int c)
{
I=a;
b=c;
}
void put()
{
cout<<"Area is : "<<I*b <<endl;
}
};
void main()
{
clrscr();
rec obj[3]={rec(3,6),rec(2,5),rec(5,5)};
cout<<"Displaying Areas of Rectangles : \n";
for(int i=0;i<3;i++)
obj[i].put();
getch();
}
81
Pointers
and
dynamic objects in C++
Computer Memory
… … 100
a
… 1024 …
Variable a’s value, i.e., 100, is
int a = 100; stored at memory location 1024
Pointers
• A pointer is a variable used to store the
address of a memory cell.
• We can use the pointer to reference this
memory cell
… … 100 … 1024 …
integer
pointer
Pointer Types
• Pointer
– C++ has pointer types for each type of object
• Pointers to int objects
• Pointers to char objects
• Pointers to user-defined objects
(e.g., RationalNumber)
– Even pointers to pointers
• Pointers to pointers to int objects
Pointer Variable
Examples:
int *n;
RationalNumber *r;
int **p; // pointer to pointer
Address Operator &
• The "address of " operator (&) gives the memory
address of the variable
– Usage: &variable_name
… … 100 … … …
a
int a = 100;
//get the value,
cout << a; //prints 100
//get the memory address
cout << &a; //prints 1024
Address Operator &
Memory address: 1020 1024 1032
… 88 100 … … …
a b
#include <iostream>
using namespace std;
Result is:
void main(){ The address of a is: 1020
int a, b; The address of b is: 1024
a = 88;
b = 100;
cout << "The address of a is: " << &a << endl;
cout << "The address of b is: " << &b << endl;
}
Pointer Variables
Memory address: 1020 1024 1032
… 88 100 … 1024 …
a p
int a = 100; Result is:
int *p = &a; 100 1024
cout << a << " " << &a <<endl; 1024 1032
cout << p << " " << &p <<endl;
58 58 58
Dereferencing Operator *
• We can access to the value stored in the variable pointed
to by using the dereferencing operator (*),
… 88 100 … 1024 …
a p
int a = 100;
int *p = &a; Result is:
cout << a << endl; 100
cout << &a << endl; 1024
cout << p << " " << *p << endl; 1024 100
cout << &p << endl; 1032
Don’t get confused
• Declaring a pointer means only that it is a pointer: int
*p;
• Don’t be confused with the dereferencing operator, which
is also written with an asterisk (*). They are simply two
different tasks represented with the same sign
int a = 100, b = 88, c = 8;
int *p1 = &a, *p2, *p3 = &c;
p2 = &b; // p2 points to b
p2 = p1; // p2 points to a
b = *p3; //assign c to b
*p2 = *p3; //assign c to a Result is:
cout << a << b << c; 888
Another Pointer Example
#include <iostream> Let’s figure out:
using namespace std; value1==? / value2==?
int main (){ Also, p1=? p2=?
int value1 = 5, value2 = 15;
int *p1, *p2;
p1 = &value1; // p1 = address of value1
p2 = &value2; // p2 = address of value2
*p1 = 10; // value pointed to by p1=10
*p2 = *p1; // value pointed to by p2= value
// pointed to by p1
p1 = p2; // p1 = p2 (pointer value copied)
*p1 = 20; // value pointed to by p1 = 20
cout << "value1==" << value1 << "/ value2==" <<
value2;
return 0;
}
Reference Variables
A reference is an additional name to
an existing memory location
Pointer: Reference:
x 9 x
9
ref
ref
int x = 9;
int x=9;
int &ref = x;
int *ref;
ref = &x;
Reference Variables
• A reference variable serves as an alternative name for an
object
int m = 10;
int &j = m; // j is a reference variable
cout << “value of m = “ << m << endl;
//print 10
j = 18;
cout << “value of m = “ << m << endl;
// print 18
Reference Variables
• A reference variable always refers to the same
object. Assigning a reference variable with a
new value actually changes the value of the
referred object.
• Reference variables are commonly used for
parameter passing to a function
Traditional Pointer Usage
void IndirectSwap(char *Ptr1, char *Ptr2){
char temp = *Ptr1;
*Ptr1 = *Ptr2;
*Ptr2 = temp;
}
int main() {
char a = 'y';
char b = 'n';
IndirectSwap(&a, &b);
cout << a << b << endl;
return 0;
}
Pass by Reference
void IndirectSwap(char& y, char& z) {
char temp = y;
y = z;
z = temp;
}
int main() {
char a = 'y';
char b = 'n';
IndirectSwap(a, b);
cout << a << b << endl;
return 0;
}
Pointers and Arrays
The name of an array points only to the first element
not the whole array.
1000
1004
1008
1012
1016
Array Name is a pointer constant
#include <iostream>
using namespace std;
Result:
Address of a[0]: 0x0065FDE4
Name as pointer: 0x0065FDE4
Dereferencing An Array Name
#include <iostream>
a[0] 2 using namespace std;
a void main(){
a[1] 4
int a[5] = {2,4,6,8,22};
a[2] 6 cout << *a << " "
<< a[0];
a[3] 8 } //main
a[4] 22
a
Array Names as Pointers
To access an array, any pointer to the first element can
be used instead of the name of the array.
We could replace *p by *a
#include <iostream>
a p using namespace std;
void main(){
a[0] 2 int a[5] = {2,4,6,8,22};
a[1] 4 int *p = a;
a[2] 6 cout << a[0] << " "
<< *p;
a[3] 8 }
a[4] 22
a
Pointer Arithmetic
Given a pointer p, p+n refers to the element that is
offset from p by n positions.
a 2 p - 1
a + 1 4 p
a + 2 6 p + 1
a + 3 8 p + 2
a + 4 22 p + 3
Dereferencing Array Pointers
a[0] or *(a + 0) 2 a
a[1] or *(a + 1) 4 a + 1
a[2] or *(a + 2) 6 a + 2
a[3] or *(a + 3) 8 a + 3
a[4] or *(a + 4) 22 a + 4
new
delete
{ int* ptr;
int a[200]; ptr = new int[200];
… …
} delete [] ptr;
Object (variable) creation: New
Syntax
ptr = new SomeType;
Example
int* p = new int;
p
Object (variable) destruction: Delete
Syntax
delete p;
storage pointed to by p is returned to free store and p is now undefined
Example
int* p = new int;
*p = 10;
delete p;
p 10
Array of New:
dynamic arrays
• Syntax
P = new SomeType[Expression];
– Where
• P is a pointer of type SomeType
• Expression is the number of objects to be
constructed -- we are making an array
new
p
new
p = new int[n]; p
Memory Allocation Example
Want an array of unknown size
#include <iostream>
using namespace std;
void main()
{
int n;
cout << “How many students? “;
cin >> n;
int *grades = new int[n];
for(int i=0; i < n; i++){
int mark;
cout << “Input Grade for Student” << (i+1) << “ ? :”;
cin >> mark;
grades[i] = mark;
}
. . .
printMean( grades, n ); // call a function with dynamic array
. . .
}
Freeing (or deleting) Memory
Dangling Pointer Problem
int *A = new int[5];
for(int i=0; i<5; i++)
A[i] = i;
int *B = A;
A
0 1 2 3 4
B
delete [] A;
B[0] = 1; // illegal!
A —
?
B
A Dynamic 2D Array
A dynamic array is an
array of pointers to save
table 32 18 12 24
space when not all rows table[0]
of the array are full. table[1] 13 11 16 12 42 19 14
int **table; table[2]
22
table[3]
table[4] 13 13 14
table[5]
11 18
table = new int*[6];
…
table[0] = new int[4];
table[1] = new int[7];
table[2] = new int[1];
table[3] = new int[3];
table[4] = new int[2];
table[5] = NULL;
Memory Allocation
int **table;
int m, n;
int m, n;
cin >> m >> n >> endl;
cin >> m >> n >> endl; int** mat;
mat = imatrix(m,n);
…
int** mat;
int** imatrix(nr, nc) {
mat = new int*[m]; int** m;
m = new int*[nr];
for (int i=0;i<nr;i++)
for (int i=0;i<m;i++) m[i] = new int[nc];
mat[i] = new int[n]; return m;
}
Self Referential Structures
• Self Referential structures are those structures
that have one or more pointers which point to
the same type of structure, as their member.
122
Types of Self Referential Structures
123
Double link
struct node {
int data;
struct node* prev_link;
struct node* next_link;
};
124
Standard Template Library
STL is a general-purpose C++ library of generic algorithms and data structures.
1. Containers store collections of objects
– vector, list, deque, set, multiset, map, multimap
2. Iterators traverse containers
– random access, bidirectional, forward/backward ...
3. Function Objects encapsulate functions as objects
– arithmetic, comparison, logical, and user-defined ...
4. Algorithms implement generic procedures
– search, count, copy, random_shuffle, sort, ...
5. Adaptors provide an alternative interface to a component
– stack, queue, reverse_iterator, ...
125
An STL Line Reverser
#include <iostream>
#include <stack> // STL stacks
#include <string> // Standard strings
void rev(void)
{
typedef stack<string> IOStack; // instantiate the template
IOStack ioStack; // instantiate the template class
string buf;
127
Syntax
try
{
throw something;
}
catch (something)
{
// Do whatever has to be done here.
}
catch (…) :: Catches everything.
128
Syntax
try
{
throw something;
}
catch (something)
{
// Do whatever has to be done here.
}
catch (…) :: Catches everything.
129
Data File Handling
in C++
INTRODUCTION
Computer programs are associated to work
with files as it helps in storing data &
information permanently.
File - itself a bunch of bytes stored on some
storage devices.
In C++ this is achieved through a component
header file called fstream.h
The I/O library manages two aspects- as
interface and for transfer of data.
The library predefine a set of operations for
all file related handling through certain
classes.
The fstream.h header file
A stream is a general term used to name flow
of data.
Example :
fout.close();
Steps To Create A File
1. Declare an object of the desired file stream class(ifstream,
ofstream, or fstream)
Syntax
Stream_object.eof( );
Example :
fout.eof( );
Text File Functions
get() – read a single character from text file and store in a
buffer.
e.g file.get(ch);
e.g. file.put(ch);
147