You are on page 1of 47

C++ Overview

CS 250 Data Structures and Algorithms


Prof. Dr. Faisal Shafait

1 / 47
Review C++

Learning Objectives

In this lecture you will


Revise the basics of C++ concepts: Classes, Pointers, Arrays,
References, Dynamic Memory Allocation and Memory Leaks

2 / 47
Review C++

Input and Output

3 / 47
Review C++

Input and Output

4 / 47
Review C++

Input and Output

5 / 47
Review C++

Command-line Arguments
Your program can gain access to the command line arguments as
follows:

1 int main( int argc , char * argv [] )


2 {
3 int i;
4 for ( i = 1; i < argc; ++i ) {
5 std:: cout << argv[i];
6 }
7 return 0;
8 }

argc is the argument counter specifying how many arguments


separated by spaces
the program name is also considered an argument
argc will always be equal to or greater than one.
argv is the array of pointers to string literals representing the
arguments.
6 / 47
Review C++

Command-line Arguments

Your program can gain access to the command line arguments as


follows:
if a program is invoked by the command

C:\> program.exe Hello World

argc will be set to 3, and argv will store values as follows:

argv:
1012 ----> "program.exe"
1023 ----> "Hello"
1045 ----> "World"
0

where 1012, 1023, and 1045 are arbitrary addresses of the


corresponding string literals in memory.
7 / 47
Review C++

Classes

Are a method to create new data types


e.g. a vector or matrix type
Object oriented programming:
Instead of asking: “What are the subroutines?"
We ask:
What are the abstract entities?
What are the properties of these entities?
How can they be manipulated?
Then we implement these entities as classes.
Advantages:
High level of abstraction possible
Hiding of representation dependent details
Presentation of an abstract and simple interface
Encapsulation of all operations on a type within a class
allows easier debugging
8 / 47
Review C++

Classes

Classes are collections of members:


functions
data
types
representing one entity
These members can be split into:
public, accessible interface to the outside
should not be modified later!
private, hidden representation of the concept
can be changed without breaking any program using the class
this is called data hiding
Objects of this type can be modified only by these member
functions -> easier debugging.

9 / 47
Review C++

How to design classes

ask yourself some questions


what are the logical entities (nouns)?
classes
what are the internal state variables ?
private data members
how will it be created/initialized and destroyed?
constructor and destructor
what are its properties (adjectives)?
public constant member functions
how can it be manipulated (verbs)?
public operators and member functions

10 / 47
Review C++

A first class example: a traffic light

Property
The state of the traffic light (green, orange or red)
Operation
Set the state
Construction
Create a light in a default state (e.g. red)
Create a light in a given state
Destruction
Nothing special needs to be done
Internal representation
Store the state in a variable

11 / 47
Review C++

A first class example: a traffic light

Converting the design into a class

1 class Trafficlight {
2
3 };

12 / 47
Review C++

A first class example: a traffic light

Add a public type member

1 class Trafficlight{
2 public: // access declaration
3 enum light { green , orange , red }; // type member
4
5 Trafficlight (); // default constructor
6 };

13 / 47
Review C++

A first class example: a traffic light

Add a private data member (variable) of that type:

1 class Trafficlight {
2 public: // access declaration
3 enum light { green , orange , red }; // type member
4
5 Trafficlight (); // default constructor
6 Trafficlight(light); // constructor
7
8 ~ Trafficlight (); // destructor
9
10 void set_state(light);
11
12 private: // this is hidden
13 light state_; // data member
14 };

14 / 47
Review C++

A first class example: a traffic light

Add a const member function to access the state

1 class Trafficlight {
2 public: // access declaration
3 enum light { green , orange , red }; // type member
4
5 Trafficlight (); // default constructor
6 Trafficlight(light); // constructor
7
8 ~ Trafficlight (); // destructor
9
10 light state () const; // function member
11
12 private: // this is hidden
13 light state_; // data member
14 };

15 / 47
Review C++

A first class example: a traffic light

Add a non-const member function to change the state

1 class Trafficlight {
2 public: // access declaration
3 enum light { green , orange , red }; // type member
4
5 Trafficlight (); // default constructor
6 Trafficlight(light); // constructor
7
8 ~ Trafficlight (); // destructor
9
10 light state () const; // function member
11
12 void set_state(light);
13
14 private: // this is hidden
15 light state_; // data member
16 };

16 / 47
Review C++

A first class example: a traffic light


Add a default constructor to initialize it in the default way
a constructor has the same name as the class

1 class Trafficlight {
2 public: // access declaration
3 enum light { green , orange , red }; // type member
4
5 Trafficlight (); // default constructor
6 Trafficlight(light); // constructor
7
8 ~ Trafficlight (); // destructor
9
10 light state () const; // function member
11
12 void set_state(light);
13
14 private: // this is hidden
15 light state_; // data member
16 };

17 / 47
Review C++

A first class example: a traffic light

Add a second constructor to construct it from a light

1 class Trafficlight {
2 public: // access declaration
3 enum light { green , orange , red }; // type member
4
5 Trafficlight (); // default constructor
6 Trafficlight(light=red); // constructor
7
8 ~ Trafficlight (); // destructor
9
10 light state () const; // function member
11
12 void set_state(light);
13
14 private: // this is hidden
15 light state_; // data member
16 };

18 / 47
Review C++

A first class example: a traffic light


And finish by adding a destructor (called to cleanup at destruction) a
destructor has the same name as the class, prefixed by ∼.

1 class Trafficlight {
2
3 public: // access declaration
4 enum light { green , orange , red }; // type member
5
6 Trafficlight(light=red); // constructor
7
8 ~ Trafficlight (); // destructor
9
10 light state () const; // function member
11
12 void set_state(light);
13
14 private: // this is hidden
15 light state_; // data member
16 };

19 / 47
Review C++

C++ Code Structure

In C++, source code is split into two files:


Header files (TrafficLight.h): contains the class definition /
interface
Implementation files (TrafficLight.cpp): contains the class
implementation

20 / 47
Review C++

Classes: Header Files

1 // TrafficLight.h
2 class Trafficlight {
3
4 public: // access declaration
5 enum light { green , orange , red }; // type member
6
7 Trafficlight(light=red); // constructor
8
9 ~ Trafficlight (); // destructor
10
11 light state () const; // function member
12
13 void set_state(light);
14
15 private: // this is hidden
16 light state_; // data member
17 };

21 / 47
Review C++

Classes: Source Files

1 // TrafficLight.cpp
2 #include " TrafficLight .h"
3 Trafficlight :: Trafficlight (light=red){ // constructor
4 state_ = light;
5 }
6
7 Trafficlight :: light Trafficlight :: state (){ // constructor
8 return state_;
9 }
10
11 void Trafficlight :: set_state(light){ // constructor
12 state_ = light;
13 }

22 / 47
Review C++

Classes: declaration

To initialize a class object:

1 Trafficlight oTrafficlight ;

OR

1 Trafficlight * classPtr;
2 classPtr = new Trafficlight;

23 / 47
Review C++

Pointer

A pointer is a variable that contains the address of a variable.

24 / 47
Review C++

Pointer

The unary operator & assigns the address of a variable to a pointer,

pc = &c;

Here, assigns the physical address of variable c to the variable pc.

25 / 47
Review C++

Pointer

Two uses of the asterisk *:


Create pointer: the declaration of the pointer p appears as

int * p;

p is a pointer to an integer variable.


Access what the pointer points to: the unary operator *p is the
indirection or dereferencing operator.

std:: cout << * p;

26 / 47
Review C++

Pointer

Use of * and & unary operators.

using variables using pointers to variables

1 int a = 5; 1 int * pa; pa = &a;


2 int b = 10; 2 int * pb; pb = &b;
3 int c; 3 int * pc; pc = &c;
4 c = a + b; 4 * pc = * pa + * pb;

27 / 47
Review C++

Pointer: vocalization

How to pronounced this in plain English?

int * p;

The pointer declaration int* ptr; can be vocalized backwards:

p; "p is ..."
* "...a pointer to ..."
int "...an integer."

28 / 47
Review C++

Pointer

Pointers are variables


they can be used without dereferencing:

pb = pa;
pc = pa;

Pointers are constrained to point to a particular kind of object;


every pointer points to a specific data type.

29 / 47
Review C++

String Literals

Consider,

std:: cout << "Hello";

"Hello" is stored in memory as a sequence of bytes, terminated with the


null character ’\0’.

H e l l o \0

Pointer to store the address of the first byte, or first character ’H’.

char * pchar = "Hello";

30 / 47
Review C++

Pointers: function arguments

Pointers as function arguments

1 void print( char * message )


2 {
3 std:: cout << message;
4 }
5
6 int main ()
7 {
8 print( "Hello" );
9 return 0;
10 }

31 / 47
Review C++

Pointers: function arguments

Another example:

1 int main ()
2 {
3 char * pmessage;
4 pmessage = "Hello";
5 print( pmessage );
6 return 0;
7 }

32 / 47
Review C++

Pointers: example

Implementing swap() function


Consider a function to swap values of two integer variables.

void swap( int x, int y ) {...}

Here, the parameters are passed by value,


actual arguments remain unaffected, as the function receives
copies of the original values.
More realistic solution is to use pointers:

void swap( int * px , int * py ) {...}

the parameters are passed by reference.


the function can access and change objects within the function

33 / 47
Review C++

Pointers: example

A complete example might look like this:

1 void swap( int * px , int * py )


2 {
3 int temp = * px;
4 * px = * py;
5 * py = temp;
6 }
7
8 int main ()
9 {
10 int a = 5;
11 int b = 10;
12 swap( a, b ); // wrong! address of the variable must be ←-
taken
13 swap( &a, &b ); // correct
14 assert( a == 10 && b == 5 );
15 return 0;
16 }

34 / 47
Review C++

References

References are alternative names for variables.


they can be used instead of pointers
they simplify notation
For example, the above swap function could be rewritten as:

1 void swap( int& x, int& y )


2 {
3 int temp = x;
4 x = y;
5 y = temp;
6 }
7 int main ()
8 {
9 int a = 5;
10 int b = 10;
11 swap( a, b );
12 assert( a == 10 && b == 5 );
13 return 0;
14 }
35 / 47
Review C++

Pointers: summary
An address &x tells where the variable is located in memory.
Pointer points to a variable by remembering its address:

ptr = &x;

Pointers are variables and must be declared:

double * d_ptr;

Here, asterisk * identifies d_ptr as a pointer variable.


The phrase “variable pointed to by pointer ptr" is translated into
C++ as

* ptr

where * is the dereference operator.


36 / 47
Review C++

Pointers and Arrays

Pointers and arrays are closely related.

1 char amessage [] = "hello"; // array


2 char * pmessage = "hello"; // pointer

Construction of the arrays of pointers is also allowed.


use of arrays of pointers is to store character strings of variable
lengths.

char * months [] = { "Illegal month", "Jan", "Feb", "Mar" };

37 / 47
Review C++

Pointer arithmetic

For any pointer T *p; the following holds:


p[n] is the same as *(p+n);
adding and integer n to a pointer increments it by n times the size
of the type – and not by n bytes

38 / 47
Review C++

Pointer arithmetic

For any pointer T *p; the following holds:


Increment ++ and decrement −− increase/decrease by one
element

Be sure to only use valid pointers


initialize them
do not use them after the object has been deleted!
catastrophic errors otherwise
39 / 47
Review C++

Dynamic memory allocation


When one defines a variable in C++,
the compiler allocates memory for that variable automatically
when the program begins running.
data structure declared this way is called a static structure.
it never changes size for the duration of the run of the program.
Consider,

1 float x[10]; // allocates memory for 10 numbers

Allocation of flexible size,

1 unsigned int n;
2 std::cin >> n;
3 float x[n]; // will not work

The compiler has to know the number!


Solution: dynamic allocation
40 / 47
Review C++

Dynamic memory allocation: new command

When you want to allocate memory while the program is running,


it is done using dynamic memory allocation.
a structure created this way is called a dynamic structure.
In C++, dynamic memory allocation is done using the new command.
takes a type as an argument
allocates enough memory to hold a variable of that type.
and, returns the address of the newly allocated memory.
The returned address should then be stored in a pointer.

MyTypePtr = new MyType;

MyType is some type (int, float, a structure or a class), and MyTypePtr is


a pointer to a MyType.

41 / 47
Review C++

Dynamic memory allocation: new command

Examples:
dynamically allocates memory for a single int, and stores the
address in intPtr.

1 int * intPtr;
2 intPtr = new int;

dynamically allocates memory for a single int, initializes it to the


value 6, and stores the address in intPtr.

1 int * intPtr;
2 intPtr = new int (6);

42 / 47
Review C++

Dynamic memory allocation: arrays

To dynamically allocate an array, specify the array size in square


brackets [] after the type:

1 float * x = new float[n]; // allocate some memory for an array


2 x[0] = 3.0f; // do some work with the array x
3 ...

To delete a dynamically allocated array, you must include a pair of


empty square brackets,

1 delete [] x; // delete the memory for the array.


2 // x[i], * x now undefined!

43 / 47
Review C++

Dynamic memory allocation: delete command

To deallocate memory which has been allocated dynamically, use the


delete command:

1 delete intPtr; // Deallocates memory pointed to by


2 // intPtr.

delete command does NOT delete the variable intPtr itself,


it deallocates the memory whose address is stored in intPtr.
and, makes it available for future allocation

44 / 47
Review C++

Memory leaks

A memory leak occurs when a computer program incorrectly manages


memory allocations.
Illegal memory accesses (segmentation faults)
Stack overflow
Infinite recursions
Double frees
Dangerous use of uninitialized variables

45 / 47
Review C++

Memory leaks

Since memory is user managed, there can be mistakes.


Memory leaks = allocated memory that’s not freed.
Why it matters?

1 #include <stdlib.h>
2
3 int main ()
4 {
5 char * x = (char * ) malloc (100); // Memory Leak!
6
7 return 0;
8 }

Allocation profilers: valgrind (linux), _CrtDumpMemoryLeaks (Visual


Studio).

46 / 47
Review C++

Reading Material

For further reading, please refer to


Data Structures by Weiss: Overview of Chapter 1 & 2

47 / 47

You might also like