You are on page 1of 58

INTRODUCTION TO C++

Course: Data Structures


Department: Computer Science

Index

C++ in short
Fundamentals
Clases
Objects

C++ in short (1/2)

Designed by Bjarne Stroustrp in the mid 80s.


Originally an extension of C

With object oriented programming mechanisms

Then tools for general programming were also included

Standard version called ISO C++

Very powerful language

It enables low level as well as high level programming


Permits to redefine (overload) operators and to create new
types of operators that work like primitive operators
Supports multiple inheritance

C++ in short (2/2)

Bibliography

Stroustrup, B. 1997. The C++ programming


language. 3rd Ed.. Addison-Wesley.

Eckel, B. 2003 Thinking in C++ Vols. 1&2. 2nd Ed.


Prentice-Hall. Available at:
http://mindview.net/Books/TICPP/ThinkingInCPP2e.html

Software

In the laboratory we will use CodeLite 6.1

Freely available at: http://codelite.org/

A classic: Hello world!


#include <iostream>
#include <stdlib.h>
int main()
{
std::cout << "Hello brave new
world!\n";
return 0;
}

Basic Data Types


Booleans (bool): to
Characters:char,
Any variant of the ISO-646, p.e. ASCII).
Usually 8-bits lenght (256 values)
Integers:int, short o long
Floating point:float,double(default for literals) and long
double
Enumerations: enum
Pointers:bool*,int*,short*,...
Arrays:bool[], int[],...
Classes

Basic Data Types


Size in bits of every type

Literals
Literal characters between single quoter: a, b,
Integer constants:
Decimal (0,45,) hex. (0x3f, 0x78,) octal (012, 023,)

Floating point numbers:


1.23

1.2e10

1.23e-15

3.141592f (f or F to compel float)

Examples of use:
bool a = true;
char ch = a;

bool b = false;
unsigned int num = 015;

bool c = a+b; //true


float fc = 1.2e-40;

Void
Syntactically is a fundamental type
No objects of this type exist!!!
Mainly used to:
indicate that a function does not return any value
is the basis for pointers to objects of an unknown
datatype

Enumerations (enum)
Store a set of values defined by the programmer
The range is set from 0 (if the lower value is not
negative) to the nearest power of 2 (on the right
side)
enum flag { x=1, y=2, e=8};
flag f1 = flag(5);

Pointers
A pointer store an address of another object
Also any address in memory (dangerous)

Pointers can point:


exclusively to objects of a defined datatype (p.e. char*)
any type (void*)
Reference operator (&) returns the address of the object.
Dereference operator (*) returns the object that is being pointed.

Examples:
char c = a;

char* p = &c; //p to the address of c

char c2 = *p; // c2==a

Arrays
An array is a set of indexed values of same type
The index is a natural number (starting on 0)
Examples:
float f[3];
int n[2][3][4];
Declaration and initialization
char c[3] = { a, b, c };
More examples:
int v[4]= { 1, 2, 3}; // The last element will be 0
char p[] = Hello world! ; // 13 elements lenght!

Pointers to arrays
Name of array = pointer to the first element
int v[] = {1, 2, 3, 4};
int* p1=v; //pointer to the first element
int* p2=&v[0]; //pointer to first element
int* p3=&v[3]; //pointer to the last element

Pointers can loop through arrays (P. arithmetic):


void f(char v[])
{
for(char* p=v; *p!=0; p++)
}

do_something(*p);

Constants
Consants are declared using the keyword
const.
Constants must be initialized when they are
declared

Structures
Aggregate of different dataypes, e.g.:
struct name
{
char* firstname;
char* lastname;
};
name jd = { John, Smith};

Elements are accessed using the dot notation:


name.lastname = "John2";

Advices
To improve code readability and maintenability:
Avoid non-trivial pointer aritmethic
Do not read or write beyond the bounds of an array
Use 0 instead of NULL
Use strings (Strings) instead of arrays of char
Avoid *void except when writing low level code
Avoid non-trivial literals

Basic I/O
C++ input and output is performed using streams
Two standard streams:
std::in
std::out

for keyboard input


for console output

Syntax to:
send information to stream is <<
receive information from a stream is >>
char c;
std::cin >> c; //read
std::cout << c; //write

Conditionals
Statements used to create conditional constr.:
if (condition) statement
if (condition) statement else statement
switch (condition) statement
if (a<=b)
max = b;
else
max = a;

enum keyword {ASM, AUTO, BREAK};


void f(keyword key)
{
switch (key)
{
case ASM:
// do something
break;
case BREAK:
// do something
break;
}
}

Iteration
while (condition) statement
do statement while (expression);
for (init-statement; condition; expression) statement
int i = 1;

int i = 1;

while(i <= 20)

do

cout << i;

cout << i;

i++;

i++;
} while(i <= 20)

for (init ; cond; expr) statement


Init is the initialization,

located = false;

cond is the condition to loop and

li = 0; lj=0;

expr is the instruction for iteraration

for ( i = 0; i < n; i++)


for ( j = 0; j < m; j++)
if (nm [i] [j] == a)
{
located = true;
li = i;
lj = j;
}
nm[li] [lj] ==a;

Arithmetic operators
Operator Name

Syntax

Operator Name

Syntax

Plus

+a

Assignment by
Subtraction

a -= b

Addition (Sum)

a+b

Multiplication
(Product)

a*b

Prefix increment

++a

Assignment by
Multiplication

a *= b

Postfix increment

a++

Division (Quotient)

a/b

Assignment by
Addition

a += b

Assignment by
Division

a /= b

Unary Minus
(Negation)

-a

Modulus
(Remainder)

a%b

Subtraction
(Difference)

a-b

Assignment by
Modulus

a %= b

Postfix decrement

--a

Logic and Comparing operators


Operator Name

Syntax

Operator Name

Syntax

Less Than

a<b

Not Equal To

a != b

Less Than or Eq. To a <= b

Equal To

a == b

Greater Than

a>b

Logical Negation

!a

Greater than or equal to

a >= b

Logical AND

a && b

Logical OR

a || b

Bit operators
Operator Name

Syntax

Operator Name

Syntax

Bitwise Left Shift

a << b

Assignment by
Bitwise AND

a &= b

Assignment by
Bitwise Left Shift

a <<= b

Bitwise OR

a|b

Bitwise Right Shift

a >> b

Assignment by
Bitwise OR

a |= b

Assignment by
Bitwise Right Shift

a >>= b

Bitwise XOR

a^b

Bitwise One's
Complement

~a

Assignment by
Bitwise XOR

a ^= b

Bitwise AND

a&b

Advices
Use the standard library whenever possible
Avoid difficult expressions
Use parenthesis
Avoid difficult castings
Avoid goto
Avoid do-statement
Do not declare varibles if they dont have an initial value.

Example: Primality test


{

#include <stdio.h>
#include <stdlib.h>

while(div > 1)
{
det = det * (num % div);

#include <iostream>
using namespace std;
int main()
{

div--;
}
if (det == 0)
cout << "The number is not prime" << endl;

int num, det=1, div;

else

cout << "Insert a number";


cin >> num;
div = num - 1;
if (num > 3)

cout << "The number is prime" << endl;


}
else
cout << "The number is prime"<< endl;
system("PAUSE");
return 0;

Example: Bubble sort (I)


int main()

#include <stdio.h>

#include <stdlib.h>

int vector[T];

#include <iostream>

for (int i=0; i < T; i++)

#define T 10

{
cout << "Insert number " << (i+1) << ":\t";
cin>>vector[i];

using namespace std;

void order(int[]);

order(vector);
for (int m=0; m < T; m++) cout<< vector[m] << " ";
cout << endl;
system("PAUSE");
return 0;
}

Example: Bubble sort (II)


void order(int vect[])
{
for (int i=0; i < T; i++)
{
for (int k=0; k < T-1; k++)
{
if(vect[k] > vect[k+1])
{
int a = vect[k];
vect[k] = vect[k+1];
}
}
}
}

vect[k+1] = a;

Functions
The declaration of a function provides:
The name of the function
The type of returned value (if any)
The number and types of arguments
On calls to functions, datatypes are checked.
Implicit castings are performed if necessary.

Functions (y2)
Every function must be declared somewhere.
A definition is a declaration that also includes the main body of
the function
On declaration is not necessary to indicate the name of the
arguments.
On definitions is not required too if arguments are not used but
just declared for compatibility issues.
Arguments can be declared inline so that the compiler
generates code and not a call to the function.
Static variables are shared for all calls to the function.

Example
extern void swap(int*, int*, char*) //declaration
void swap(int* p, int* q, char* ) //definition
{
int t = *p;
*p = *q;
*q = t;
}
inline int sum(int a, int b)
{
return a+b;
}

Arguments
Semantics of arguments is similar to their initialization
Datatypes are checked.
Implicit castings are performed if necessary
Arguments can be by value or by reference
Arguments by reference are pointers
Const can be used on arguments by reference to prevent them
from being modified
Arrays are always arguments by reference
Default values could be used on arguments

Examples
void f(int value, int& reference)
{
value++; //increment the local copy
reference++;//increment the original variable
}
void g(const int& parameter) //parameter will not be changed

void h(const char* array) //an array that cannot be modified


void i(int a, int b=10) //a call i(8) is permitted

Returned values
A function returns a value if it has not been
declared as void
References to local variables should not be
returned (their memory space is reassigned when
the function returns)
void f() {return i; } // Wrong!
int& g() {return local;} // Wrong!
int* h() {return &local;} // Fatal!

Function overload
Different functions can have the same name
The compiler will select the appropiate function to call
according to the deatatypes of expressions and arguments:
Exact match or with trivial conversions (e.g. a name of an array
to a pointer)
Match using promotions of similar datatypes (e.g. bool to int,
char to int, float to double)
Match using standard castings (e.g. int to double, int* to void*)
Match using user-based castings.
Returned values are not considered for overloads.

More on functions
Functions with an undetermined number of
arguments can be declared.
Pointers to functions are allowed.
They can be used to call the functions.
Macros are permitted.
They can be used for conditional compilations.

Organizing your code


.h: files to include with directive #include.
They contain declarations, definitions of datatypes,
classes,
#include <stdio.h> use <> for general libraries
#include my.h use for files in the local drive
.c/.cpp: standard extensions for source code

Advices
Be careful with arguments by reference that do not
use const
Avoid macros
Avoid functions with an undetermined number of
arguments
Do never return references to local variables

CLASSES

Clases
Classes are user-defined datatypes
Classes have:
propertites (attributes)
methods (actions that can perform)
constructors to initialize objects of that class (properties, )
may have static properties and/or methods that are shared by
all the instances of the class

Privacy
Classes may have
Public and private
Methods and properties

The keyword public: is for public members


All other members are private
Can only be used by other functions members of the class

Constructors
Special method, to initialize the object
Same name that the class have
Can be overloaded
Default values can be interesting for constructors
Instead of creating multiple constructors

Static members
Classes may have static members
Static keyword is used
Static members are part of the class instead of being part
of objects (instances)
Access to static members the name of the class is used
instead of the name of the object.

Constant functions
Methods declared using const
Not allowed to modify the object (properties)
Some properties can be changed from constant functions
They are declared as mutable

Example
class Date
{
int year;

int month;

public:
void print() const;
void Date();
}
void Date::print() {}

int day;

Self-reference
Non-static methods can use the keyword this
Reference to the object

Exercices
Implement a class called Date to store dates
The constructor/s can get 3 integer arguments (day,
month, year) and can be called with 0, 1, 2 or 3
arguments. Not present arguments shall be replaced by
default arguments. Default date must be common and
shall not be modified.
Include functions to update and get the different elements
of the date (day, month, year)
Create a function to decide whether a date is more recent
than other (both dates can be arguments)

Exercices
Implement a class called Person with information about
people. Include
Constructor/s with 3 arguments (FirstName,
LastName y Birthday), that can be called using 2 or
3 arguments (if birthdate is not specificied a default
date will be used). Default date must be common
and shall not be modified.
Functions to update and get the different values
A function to decide whether a person is younger
than other

Bibliography

OBJECTS

Creating objects
Objects (instances of a class) can be created:

As local variables
As global variables
As members of other classes
Dynamically
Temporally (to evaluate an expression)

Constructors y destructors
Constructors

Initialize and object

Same name of class

Classes have default constructors

Destructors

Destroy the object, disposing its memory and


performing other actions (e.g. close files,)

Same name of class with ~ at the beginning

Constructors y destructors (II)


It is necessary to create a constructor for:
Classes without a specific constructor
Classes with constants
Classes with references
Local objects:
Initialized when the execution thread
reaches its declaration
Destroyed when the functions returns or the
block in which they are declared ends

Operators new y delete


new is an operator to create a dynamic object.

It returns a reference to the newly created object

delete destroys an object

Dispose the (dynamic) memory that it is using

new[] and delete[] are used for arrays

Derived classes
A class can inherit from any other class:

The class that inherits is called subclass or derived


class

The class of which it is inherited is called superclass or


base class

The derived class may use the public and protected


members. But it will not have access to the private
members.

Example
class Employee
{
string first_name,family_name;
public:
void print() const;
};
class Manager : public Employee
{
public:
void print() const;
};

Constructors and destructors


If a class has a constructor

Derived classes must call it

If the constructor of the base class has arguments

An explicit call is required

Otherwise, it can be called implicitly

Class hierarchy
Inheritance relations create a graph-like structure

Called Class hierarchy

C++ permits multiple inheritance:


class Tsec:public Temporary, public Secretary
{...};
class Consultant:public Temporary, public
Manager{ ...};

Virtual functions
Must be redefined (overriden) on any derived class
Keyword virtual
virtual void print () const;
Create abstract classes

You might also like