Sie sind auf Seite 1von 146

Basic concept in C++

1
What is C++?

• Object-oriented programming (classes )


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

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.

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

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

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
ostream
operator overloading
(two different argument types!)
6
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.
7
1-8
Data -type Modifiers:
• Signed
• Unsigned
• Short
• Long
• Identifier naming
– ALL_CAPS for constants
– lowerToUpper for variables
– Most important: MEANINGFUL NAMES!

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;

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

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

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

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.

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

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

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

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


*iPtr = 100;

variable value Address in hex



i 100 456FD4
iPtr 456FD0
456FD4

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

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
}
32
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

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

35
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;
public:
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 {
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

Strings should support:


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

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

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


char& operator[](const int n) throw(exception);
String& operator+=(const String&) throw(exception); //
concatenation
private:
char *_s; // invariant: _s points to a null-terminated heap
string
39
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!

40
Destructors
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!
41
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
42
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”
type:
str = "hello world";

str = String("hello world");

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)

• 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

46
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.
47
Overloadable Operators
The following operators may be overloaded:

+ - * / % ^ & |

- ! , = < > <= >=

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

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

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

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

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


function.

• 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
keyword.
50
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
argument.
• 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.

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

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


OOP
Prof.A.KANNAMMAL,JCET 53
Overloading
A single function name denoting two or more function bodies is
overloaded

• 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


types

• 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

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

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

57
/Abstract base class
class Base
{
public:
virtual void show() = 0; // Pure Virtual Function
};

class Derived:public Base


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

int main()
{
Base obj; //Compile Time Error
Base *b;
Derived d;
b = &d;
b->show();
}

58
Inheritance

Inheritance is a mechanism for


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

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

62
Inheritance Concept
• Augmenting the original class
Polygon Point

Rectangle Circle 3D-Point


Triangle

• Specializing the original class


ComplexNumber real
imag

RealNumber ImaginaryNumber imag


real
63
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

Prof.A.KANNAMMAL,JCET 64
Prof.A.KANNAMMAL,JCET 65
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
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

Employee “is a” BirthDate; //Wrong!


Employee “has a” Birthdate;//Composition

Prof.A.KANNAMMAL,JCET 68
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
implementations
Prof.A.KANNAMMAL,JCET 69
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

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

derived class: sphere sphere


r
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
members:
ID, name, salary
employee()
show()
derived class: manager
members:
manager is kind of employee office, bonus
manager()
computeBonus()
show()
Inheritance Concept
class Polygon{
protected:
Polygon
int numVertices;
float *xCoord, float *yCoord;
public:
void set(float *x, float *y, int nV);
Rectangle };
Triangle

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

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

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

• 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.
Syntax:
• function_name(object_name);

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

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

Memory address: 1020 1024 1032

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

• Declaration of Pointer variables


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

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

Memory address: 1020 1024

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

• 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
*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;

void main (){


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

Result:
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
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

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


Note: flexible pointer syntax
Array of Pointers & Pointers to Array
a
p
b

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!
Dynamic
Objects
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
request
• 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

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

where ptr is a pointer of type SomeType

Example
int* p = new int;

Uninitialized int variable

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

• Because of the flexible pointer syntax, P can be


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

 int *p, n=10; new


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

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!

Locations do not belong to program

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;

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.

122
Types of Self Referential Structures

• Self Referential Structure with Single Link


• Self Referential Structure with Multiple Links

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;

while (getline(cin, buf)) {


ioStack.push(buf);
}
while (ioStack.size() != 0) {
cout << ioStack.top() << endl;
ioStack.pop();
}
}
126
Basic Exception Handling
• Try
• Throw
• Catch

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.

Streams act as an interface between files and


programs.

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.
FUNCTIONS OF FILE STREAM CLASSES
 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.
File TYPES
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
WHAT IS FILE MODE?
The File Mode describes how a file is to be used ; to
read from it, write to it, to append and so on
Syntax
Stream_object.open(“filename”,mode);
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.
Syntax:
Stream_object.close( );

Example :
fout.close();
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).

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

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
do
{ cout<<”\n enter line of text”;
gets(s); //standard input
file<<s; // write in a file myfile.txt
cout<<”\n more input y/n”;
cin>>ch;
}while(ch!=’n’||ch!=’N’);
file.close();
} //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
while(file)
{ file.get(ch) // read a
character from text file ‘
myfile.txt’
cout<<ch; // write a character in text file ‘myfile.txt ‘
}
file.close();
} //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
used
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
file.seekg(p,ios::cur)
i.e to move to p byte position from beginning, end or current
position.
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
file.seekp(p,ios::cur)
i.e to move to p byte position from beginning, end or current
position.

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

147