Sie sind auf Seite 1von 146

Basic concept in C++

What is C++?

• Object-oriented programming (classes )

• Programming-in-the-large (namespaces, exceptions)
• Generic programming (templates)
• Reuse (large class inheritance & template libraries)

Programming Paradigms
• Procedural Programming (functions)
• Modular Programming (namespaces)
• Object Oriented Programming (classes)
• Generic Programming (templates)

C++ vs C
Most C programs are also C++ programs.

• avoid macros (use inline)

• avoid pointers (use references)
• avoid malloc and free (use new and delete)
• avoid arrays and char* (use vectors and strings) ...
• avoid structs (use classes)
• avoid procedural programming
– model your domain with classes and templates
– Note:
Nevertheless, good C++ programs usually do not resemble C:

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;

“Hello World” in C++
Use the standard namespace Include standard
iostream classes

using namespace std;

A C++ comment #include <iostream>
// My first C++ program!
int main(void)
cout << "hello world!" << endl;
return 0;
cout is an
instance of
operator overloading
(two different argument types!)
Data types in C++ is mainly divided into two types:
• Primitive Data Types: These data types are built-in or predefined
data types and can be used directly by the user to declare variables.
example: int, char , float, bool etc.
– Integer
– Character
– Boolean
– Floating Point
– Double Floating Point
– Valueless or Void
– Wide Character
• This data type has size greater than the normal 8-bit datatype. Represented
by wchar_t. It is generally 2 or 4 bytes long.
• Abstract or user defined data type: These data types are defined by
user itself. Like, defining a class in C++ or a structure.
Data -type Modifiers:
• Signed
• Unsigned
• Short
• Long
• Identifier naming
– ALL_CAPS for constants
– lowerToUpper for variables
– Most important: MEANINGFUL NAMES!

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

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)

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
• The insertion operator(<<) insert the value of the variable
• 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
– 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";
Operators in C / C++

Example 1: Hello World Program

#include <iostream>

int main()
cout << "Hello, World!";
return 0;

If statements
True False
if (condition)
S1; S2
} S3

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
Assume we declared the following variables:
int a = 2, b=5, c=10;

Here are some examples of boolean conditions we can use:

• if (a == b) …
• if (a != b) …
• if (a <= b+c) …
• if(a <= b) && (b <= c) …
• if !((a < b) && (b<c)) …

If example
#include <iostream.h>

void main()
int a,b;
cin >> a >> b ;

if (a <=b)
cout << “min is “ << a << endl;
cout << “ min is “ << b << endl;
cout << “happy now?” << endl;
While statements
while (condition)

While example
//read 100 numbers from the user and output their sum
#include <iostream.h>
void main() {
int i, sum, x;
while (i <= 100) {
cin >> x;
sum = sum + x;
i = i+1;
cout << “sum is “ << sum << endl;

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
integer: ";
cout << "This is not a prime
cin >> n; number";
return 0;
Functions in C/C++

• A function is a set of statements that take

inputs, do some specific computation and
produces output.
• The idea is to put some commonly or
repeatedly done task together and make a
function, so that instead of writing the same
code again and again for different inputs, we
can call the function.

Function Declaration
• Function declaration tells compiler about
number of parameters function takes, data-
types of parameters and return type of

Difference between Call by Value and Call by
• The parameters passed to function are called actual parameters
whereas the parameters received by function are called formal

• Call By Value: In this parameter passing method, values of actual

parameters are copied to function’s formal parameters and the
two types of parameters are stored in different memory locations.
So any changes made inside functions are not reflected in actual
parameters of caller.
• Call by Reference: Both the actual and formal parameters refer to
same locations, so any changes made inside the function are
actually reflected in actual parameters of caller.

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);

printf("a=%d b=%d\n", a, b); printf("a=%d b=%d\n", a, b);

return 0; return 0;
} }
void swapx(int x, int y) void swapx(int* x, int* y)
{ {
int t; int t;

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
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
static void f()
// statement must use static variable

int main()
X::f(); // calling member function directly with class name

• 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

#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;
Pointers in C++

int i;
int *iPtr; // a pointer to an integer

iPtr = &i; // iPtr contains the address of I

*iPtr = 100;

variable value Address in hex

i 100 456FD4
iPtr 456FD0

A reference is an alias for another variable:
i,ir 10
int i = 10;
int &ir = i; // reference (alias)
ir = ir + 1; // increment i

Once initialized, references cannot be changed.

References are especially useful in procedure calls to avoid the overhead of

passing arguments by value, without the clutter of explicit pointer
dereferencing ( y = *ptr;)
void refInc(int &n)
n = n+1; // increment the variable n refers to
References vs Pointers
References should be preferred to pointers
except when:
• manipulating dynamically allocated objects
– new returns an object pointer
• a variable must range over a set of objects
– use a pointer to walk through the set

C++ Classes
C++ classes may be instantiated either automatically (on the stack):

MyClass oVal; // constructor called

// destroyed when scope ends
or dynamically (in the heap)

MyClass *oPtr; // uninitialized pointer

oPtr = new MyClass; // constructor called

// must be explicitly deleted
pointer-variable = new data-type(value);
Example: int *p = new int(25);
Allocate block of memory: new operator is also used to allocate a block(an array)
of memory of type data-type.
pointer-variable = new data-type[size];
int *p = new int[10]; 34
// memory allocation of num for (int i = 0; i < num; ++i)
number of floats {
#include <iostream> cout << "Student" << i + 1 << ":
#include <cstring> ";
using namespace std; cin >> *(ptr + i);
int main() cout << "\nDisplaying GPA of
{ students." << endl;
int num; for (int i = 0; i < num; ++i) {
cout << "Enter total number of cout << "Student" << i + 1 << " :"
students: "; << *(ptr + i) << endl;
cin >> num; }
float* ptr;
// ptr memory is released
delete [] ptr;
ptr = new float[num];
return 0;
cout << "Enter GPA of students." }
<< endl;

Constructors and destructors
Include standard iostream
and string classes
#include <iostream>
#include <string>

using namespace std;

class MyClass {
Use initialization
private: list in constructor
string name;
MyClass(string Name)
name=Name Specify cleanup
// constructor in destructor
cout << "create " << name << endl;
~MyClass() {
cout << "destroy " << name << endl;
} 36
Most of your classes should look like this:

class myClass {
myClass(void); // default constructor
myClass(const myClass& copy); // copy constructor
... // other constructors
~myClass(void); // destructor
... // other public member functions

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

Strings should support:

• creation and destruction
• initialization from char arrays
• copying
• safe indexing
• safe concatenation and updating
• output
• length, and other common operations ...

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(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

inline int length(void) const { return ::strlen(_s); }

char& operator[](const int n) throw(exception);
String& operator+=(const String&) throw(exception); //
char *_s; // invariant: _s points to a null-terminated heap
void become(const char*) throw(exception); // internal copy
Default Constructors
Every constructor should establish the class invariant:
Allocate memory
String::String(void) for the string
_s = new char[1]; // allocate a char array
_s[0] = '\0'; // NULL terminate it!

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!

The String destructor must explicitly free any memory
allocated by that object.
String::~String (void) free memory
delete [] _s;

Every new must be matched somewhere by a delete!

• use new and delete for objects
• use new[] and delete[] for arrays!
Copy Constructors
Our String copy constructor must create a deep copy:

String::String(const String& copy)

become(copy._s); // call helper

void String::become(const char* s) throw (exception)

_s = new char[::strlen(s) + 1];
if (_s == 0) throw(logic_error("new failed"));
::strcpy(_s, s);
From std
Implicit Conversion
When an argument of the “wrong” type is
passed to a function, the C++ compiler looks for
a constructor that will convert it to the “right”
str = "hello world";

str = String("hello world");

Polymorphism Definition

– Having, or assuming, various forms, characters, or
styles. Term used in several different ways in
computer science

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
• 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.

C++ Overloading (Function and Operator)

• If we create two or more members having the

same name but different in number or type of
parameter, it is known as C++ overloading. In
C++, we can overload:
– methods,
– constructors, and
– indexed properties

C++ Operators Overloading

• Operator overloading is a compile-time polymorphism

in which the operator is overloaded to provide the
special meaning to the user-defined data type.
• Operator overloading is used to overload or redefines
most of the operators available in C++.
• It is used to perform the operation on the user-defined
data type.
• For example, C++ provides the ability to add the
variables of the user-defined data type that is applied
to the built-in data types.
Overloadable Operators
The following operators may be overloaded:

+ - * / % ^ & |

- ! , = < > <= >=

++ -- << >> == != && ||

+= -= /= %= ^= &= |= *=

<<= >>= [] () -> ->* new delete

Operator that cannot be overloaded are as
• Scope operator (::)
• Sizeof
• member selector(.)
• member pointer selector(*)
• ternary operator(?:)

Syntax of Operator Overloading
return_type class_name : : operator op(argument_list)
// body of the function.

• Where the return type is the type of value returned by the


• class_name is the name of the class.

• operator op is an operator function where op is the

operator being overloaded, and the operator is the
Rules for Operator Overloading

• Existing operators can only be overloaded, but the new

operators cannot be overloaded.
• The overloaded operator contains atleast one operand
of the user-defined data type.
• When unary operators are overloaded through a
member function take no explicit arguments, but, if
they are overloaded by a friend function, takes one
• When binary operators are overloaded through a
member function takes one explicit argument, and if
they are overloaded through a friend function takes
two explicit arguments.

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.

Polymorphic Variables

Variable declared as one class can hold values

from subclass

• Dynamic (run-time) type must be subclass of static

(declared) type

• In C++, only works with pointers and references

• Polymorphic variables (or values) basis for power of

A single function name denoting two or more function bodies is

• Common example: + means both integer and floating addition

In Java, + also used for string concatenation

• Determination of which function to execute made by examining argument/return


• Bound either at compile-time or at run-time depending on language

• Should not be confused with overriding or refinement – functions need not be

related by classes

• Should not be confused with coercion (casting) – one type is converted into another
for operation

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.

Characteristics of Abstract Class

• Abstract class cannot be instantiated, but

pointers and refrences of Abstract class type can
be created.
• Abstract class can have normal functions and
variables along with a pure virtual function.
• Abstract classes are mainly used for Upcasting, so
that its derived classes can use its interface.
• Classes inheriting an Abstract Class must
implement all pure virtual functions, or else they
will become Abstract too.
Pure Virtual Functions in C++
• Pure virtual Functions are virtual functions
with no definition. They start with virtual
keyword and ends with = 0. Here is the syntax
for a pure virtual function,
• virtual void f() = 0;

/Abstract base class
class Base
virtual void show() = 0; // Pure Virtual Function

class Derived:public Base

void show()
cout << "Implementation of Virtual Function in Derived class\n";

int main()
Base obj; //Compile Time Error
Base *b;
Derived d;
b = &d;


Inheritance is a mechanism for

• building class types from existing class types
• defining new class types to be a
of existing types

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
– 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

Access Rights of Derived Classes
Type of Inheritance

private protected public

for Members
Access Control

private - - -
protected private protected protected
public private protected public

• The type of inheritance defines the access level for the

members of derived class that are inherited from the base

Inheritance Concept
• Augmenting the original class
Polygon Point

Rectangle Circle 3D-Point


• Specializing the original class

ComplexNumber real

RealNumber ImaginaryNumber imag

Different Types of Inheritance

• OOPs support the six different types of

inheritance as given below :
– Single inheritance
– Multi-level inheritance
– Multiple inheritance
– Multipath inheritance
– Hierarchical Inheritance
– Hybrid Inheritance

Base and Derived Classes

• Often an object from a derived class (subclass) “is an”

object of a base class (superclass)
Base class Derived classes

Student GraduateStudent
Shape Circle
Loan CarLoan
Employee FacultyMember
Account CheckingAccount

• 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.

Composition vs. Inheritance
• "is a" relationship
– Inheritance
• "has a" relationship
– Composition - class has an object from another class as a data

Employee “is a” BirthDate; //Wrong!

Employee “has a” Birthdate;//Composition

Advantages of inheritance

• When a class inherits from another class,

there are three benefits:
• (1) You can reuse the methods and data of
the existing class
(2) You can extend the existing class by
adding new data and new methods
(3) You can modify the existing class by
overloading its methods with your own
Inheritance and accessibility

• A class inherits the behavior of another

class and enhances it in some way
• Inheritance does not mean inheriting
access to another class’ private members

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

Concept of Inheritance (continue)
• Conceptual examples
- example 1: circle
base class: circle
area = 3.1415*r*r

derived class: sphere sphere

area = 4 *circle::area
volume = 4/3*circle::area*r
Sphere is kind of circular shape
Concept of Inheritance (continue)
- example 2:
base class: employee
ID, name, salary
derived class: manager
manager is kind of employee office, bonus
Inheritance Concept
class Polygon{
int numVertices;
float *xCoord, float *yCoord;
void set(float *x, float *y, int nV);
Rectangle };

class Triangle{
class Triangle : public Polygon{ int numVertices;
public: float *xCoord, float *yCoord;
float area(); public:
void set(float *x, float *y, int nV);
float area();
Multiple Inheritance in C++

• Multiple Inheritance is a feature of C++ where

a class can inherit from more than one classes.
• The constructors of inherited classes are
called in the same order in which they are
inherited. For example, in the following
program, B’s constructor is called before A’s

int main()
using namespace std; C c;
return 0;
class A
{ }
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.
C() { cout << "C's constructor called" << endl; }

class derived : public base
Call parent constructor {
and pass in parameter int j;
#include <iostream> derived(int x, int y): base(y){
using namespace std; j=x;
class base
cout << "Constructing derived.\n";
int i; ~derived(void) {cout << "Destructing
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);
Passing and Returning Objects in C++

• In C++ we can pass class’s objects as

arguments and also return them from a
function the same way we pass and return
other variables. No special keyword or header
file is required to do so.
• function_name(object_name);

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>
class rec
int I;
int b;
rec(int a,int c)
void put()
cout<<"Area is : "<<I*b <<endl;
void main()
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++)
dynamic objects in C++
Computer Memory

• Each variable is assigned a memory slot (the

size depends on the data type) and the
variable’s data is stored there

Memory address: 1020 1024 1032

… … 100
… 1024 …
Variable a’s value, i.e., 100, is
int a = 100; stored at memory location 1024
• A pointer is a variable used to store the
address of a memory cell.
• We can use the pointer to reference this
memory cell

Memory address: 1020 1024 1032

… … 100 … 1024 …
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

• Declaration of Pointer variables

type* pointer_name;
type *pointer_name;
where type is the type of data pointed to (e.g. int, char, double)

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

Memory address: 1020 1024

… … 100 … … …
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;

• The value of pointer p is the address of variable a

• A pointer is also a variable, so it has its own memory address
Pointer to Pointer

What is the output?

58 58 58
Dereferencing Operator *
• We can access to the value stored in the variable pointed
to by using the dereferencing operator (*),

Memory address: 1020 1024 1032

… 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
• 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==" <<
return 0;
Reference Variables
A reference is an additional name to
an existing memory location
Pointer: Reference:

x 9 x


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

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.





Array Name is a pointer constant
#include <iostream>
using namespace std;

void main (){

int a[5];
cout << "Address of a[0]: " << &a[0] << endl
<< "Name as pointer: " << a << endl;

Address of a[0]: 0x0065FDE4
Name as pointer: 0x0065FDE4
Dereferencing An Array Name

This element is called

a[0] or *a

#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
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
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

*(a+n) is identical to a[n]

Note: flexible pointer syntax
Array of Pointers & Pointers to Array

An array of Pointers A pointer to an array

int a = 1, b = 2, c = 3; int list[5] = {9, 8, 7, 6, 5};
int *p[5]; int *p;
p[0] = &a; P = list;//points to 1st entry
p[1] = &b; P = &list[0];//points to 1st entry
p[2] = &c; P = &list[1];//points to 2nd entry
P = list + 1; //points to 2nd entry
NULL pointer
• NULL is a special value that indicates an empty pointer
• If you try to access a NULL pointer, you will get an error
int *p;
p = 0;
cout << p << endl; //prints 0
cout << &p << endl;//prints address of p
cout << *p << endl;//Error!
Memory Management
• Static Memory Allocation
– Memory is allocated at compilation time
• Dynamic Memory
– Memory is allocated at running time
Static vs. Dynamic Objects
• Static object • Dynamic object
(variables as declared in function calls)

– Memory is acquired – Memory is acquired by

automatically program with an allocation
• new operation

– Memory is returned – Dynamic objects can exist

automatically when object beyond the function in which
goes out of scope they were allocated

– Object memory is returned by

a deallocation request
• delete operation
Memory Allocation

{ int* ptr;
int a[200]; ptr = new int[200];
… …
} delete [] ptr;
Object (variable) creation: New
ptr = new SomeType;

where ptr is a pointer of type SomeType

int* p = new int;

Uninitialized int variable

Object (variable) destruction: Delete
delete p;
storage pointed to by p is returned to free store and p is now undefined

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

• Because of the flexible pointer syntax, P can be

considered to be an array
Dynamic Memory Allocation
 Request for “unnamed” memory from the Operating System

 int *p, n=10; new

p = new int;
p = new int[100];


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;

0 1 2 3 4
delete [] A;
B[0] = 1; // illegal!

Locations do not belong to program

A —

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]
table[4] 13 13 14
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;

table = new int*[6];

table[0]= new int[3];

table[1]= new int[1];
table[2]= new int[5];
table[3]= new int[10];
table[4]= new int[2];
table[5]= new int[6];

table[0][0] = 1; table[0][1] = 2; table[0][2] = 3;

table[1][0] = 4;
table[2][0] = 5; table[2][1] = 6; table[2][2] = 7; table[2][3]
= 8; table[2][4] = 9;

table[4][0] = 10; table[4][1] = 11;

cout << table[2][5] << endl;
Memory Deallocation
• Memory leak is a serious bug!
• Each row must be deleted individually
• Be careful to delete each row before deleting
the table pointer.
– for(int i=0; i<6; i++)
delete [ ] table[i];
delete [ ] table;
Create a matrix of any dimensions, m by n:

Put it into a function:

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.

Types of Self Referential Structures

• Self Referential Structure with Single Link

• Self Referential Structure with Multiple Links

Double link
struct node {
int data;
struct node* prev_link;
struct node* next_link;

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, ...

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;

while (getline(cin, buf)) {

while (ioStack.size() != 0) {
cout << << endl;
Basic Exception Handling
• Try
• Throw
• Catch

throw something;
catch (something)
// Do whatever has to be done here.
catch (…) :: Catches everything.

throw something;
catch (something)
// Do whatever has to be done here.
catch (…) :: Catches everything.

Data File Handling
in C++
 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
The fstream.h header file
A stream is a general term used to name flow
of data.

Streams act as an interface between files and


A Stream is sequence of bytes.

They represent as a sequence of bytes and
deals with the flow of data.

Every stream is associated with a class having

member functions and operations for a
particular kind of data flow.
 filebuf – It sets the buffer to read and write, it contains
close() and open() member functions on it.
 fstreambase – this is the base class for fstream and,
ifstream and ofstream classes. therefore it provides the
common function to these classes. It also contains open()
and close() functions.
 ifstream – Being input class it provides input operations it
inherits the functions get( ), getline( ), read( ), and random
access functions seekg( ) and tellg( ) functions.
 ofstream – Being output class it provides output
operations it inherits put( ), write( ) and random access
functions seekp( ) and tellp( ) functions.
 fstream – it is an i/o class stream, it provides
simultaneous input and output operations.
A File can be stored in two ways
Text File
Binary File

Text Files : Stores information in ASCII characters. In text file

each line of text is terminated by with special character known
as EOL (End of Line) In text file some translations takes place
when this EOL character is read or written.
Binary File: it contains the information in the same format as
it is held in the memory. In binary file there is no delimiter for a
line. Also no translation occur in binary file. As a result binary
files are faster and easier for program to read and write.
File modes
The File Mode describes how a file is to be used ; to
read from it, write to it, to append and so on
File Modes
ios::out: It open file in output mode (i.e write mode) and
place the file pointer in beginning, if file already exist it will
overwrite the file.
ios::in It open file in input mode(read mode) and permit
reading from the file.
File modes
ios::app It open the file in write mode, and place file pointer
at the end of file i.e to add new contents and retains previous
contents. If file does not exist it will create a new file.
ios::ate It open the file in write or read mode, and place file
pointer at the end of file i.e input/ output operations can
performed anywhere in the file.
ios::trunc It truncates the existing file (empties the file).
ios::nocreate If file does not exist this file mode ensures that
no file is created and open() fails.
 ios::noreplace If file does not exist, a new file gets created
but if the file already exists, the open() fails.
ios::binary Opens a file in binary mode.
Closing a File
 A File is closed by disconnecting it with the stream it is
associated with. The close( ) function is used to
accomplish this task.
Stream_object.close( );

Example :
Steps To Create A File
1. Declare an object of the desired file stream class(ifstream,
ofstream, or fstream)

2. Open the required file to be processed using constructor or

open function.

3. Process the file.

4. Close the file stream using the object of file stream.

eof ( ) Function
This function determines the end-of-file by returning true(non-
zero) for end of file otherwise returning false(zero).


Stream_object.eof( );

Example :
fout.eof( );
Text File Functions
get() – read a single character from text file and store in a

e.g file.get(ch);

put() - writing a single character in textfile

e.g. file.put(ch);

getline() - read a line of text from text file store in a buffer.

e.g file.getline(s,80);

We can also use file>>ch for reading and file<<ch writing

in text file. But >> operator does not accept white spaces.
Program to create a text file using strings I/O

#include<fstream.h> //header file for file operations

void main()
char s[80], ch;
ofstream file(“myfile.txt”); //open myfile.txt in default output mode
{ cout<<”\n enter line of text”;
gets(s); //standard input
file<<s; // write in a file myfile.txt
cout<<”\n more input y/n”;
} //end of main
Program to read content of ‘myfile.txt’ and display it
on monitor.
#include<fstream.h> //header file for file operations
void main()
char ch;
ifstream file(“myfile.txt”); //open myfile.txt in default input mode
{ file.get(ch) // read a
character from text file ‘
cout<<ch; // write a character in text file ‘myfile.txt ‘
} //end of main
File Pointer
The file pointer indicates the position in the file at which the
next input/output is to occur.

Moving the file pointer in a file for various operations viz

modification, deletion , searching etc. Following functions are
seekg(): It places the file pointer to the specified position in
input mode of file.
e.g file.seekg(p,ios::beg); or
file.seekg(-p,ios::end), or
i.e to move to p byte position from beginning, end or current
File Pointer
seekp(): It places the file pointer to the specified position in
output mode of file.
e.g file.seekp(p,ios::beg); or file.seekp(-p,ios::end), or
i.e to move to p byte position from beginning, end or current

tellg(): This function returns the current working position of the

file pointer in the input mode.
e.g int p=file.tellg();

tellp(): This function returns the current working position of the

file pointer in the output mode.
e.f int p=file.tellp();
Java Simplifications of C++
• no pointers — just references
• no functions — can declare static methods
• no global variables — use public static variables
• no destructors — garbage collection and finalize
• no linking — dynamic class loading
• no header files — can define interface
• no operator overloading — only method overloading
• no member initialization lists — call super constructor
• no preprocessor — static final constants and automatic inlining
• no multiple inheritance — implement multiple interfaces
• no structs, unions, enums — typically not needed