Sunteți pe pagina 1din 48

Engineering and Information Technology

Advanced C++ for Java Programmers


Module 7503a
Michael Mder
Email: michael.maeder@bfh.ch
Web: https://staff.hti.bfh.ch/mdm3

Engineering and Information Technology

Advanced C++ for Java


Programmers

Semester organisation

Theoretical lecture with practical hands-on.


Two exams (will be announced)
Homework (optional, bonus for end grade)
Eventually a Mini-Project

Engineering and Information Technology

Advanced C++ for Java


Programmers

End grade

1/2 First exam


1/2 Second exam
Additional bonus (maximum 1 point) of the end grade
depending of the homework

Example:

4.5 first exam, 5 second exam and .25 points on


homework gives: (4.5 + 5)/2 + .25 = 5

Engineering and Information Technology

Information and Bibliography

Advanced C++ for Java


Programmers

Advanced C++ for Java Programmers (printed at the


schools printing service)
A lot of information can be found on the web (e.g.
Wikipedia, www.c-plusplus.de, www.cplusplus.com, ...)
The C++ Programming Language, Bjarne Stroustrup,
Addison Wesley (The C++ Bible!)
C++ in a nutshell, Ray Lischner, OReilly
Practical C++ Programming, Steve Oualline, OReilly
... and a lot more

Engineering and Information Technology

Advanced C++ for Java


Programmers

Semester agenda

The following major topics will be discussed during the


semester:

Differences and similarities


C++ specific stuff
The standard template library (STL)
Function pointers and function objects
Memory management
Casting
Runtime Type Identification (RTTI)
Code Optimization (optional)
C language compatibility issues (optional)
C++ idioms (optional)

Engineering and Information Technology

Advanced C++ for Java


Programmers

Major reasons for Java Programmers to know


C++

Native classes for Java are written in C++


Native code generation (better speed performance, less
resource wasting)
Tremendous amount of C++ programs and libraries
exist
Direct access to operating system. Hardware access
C-style pointers still exist. Useful also for hardware and
port access

Engineering and Information Technology

Differences and Similarities

Engineering and Information Technology

Advanced C++ for Java


Programmers

C++ Overview - Introduction

Developed in early 1980 by Bjarne Stroustrup


The main goals of its introduction was:
Introduce object-orientation to classical C
Be backward compatible to C
C++ design decision were made to enhance performance

Just a few standard library directly integrated with the


language. But a lot of external libraries available (not in
the scope of this course)

Engineering and Information Technology

Contribution of other languages to Java

Advanced C++ for Java


Programmers

Sim ula

A da

Sm alltalk

M odula-2

Eiffel

O bjective-C

C+ +

O bjectPascal
M odula-3
O beron-2

Java

Pascal

Engineering and Information Technology

Transformation from a C++ source code to an


executable program

Advanced C++ for Java


Programmers

High-level code
C++ source code

Compiler

Assembly-language
program

Assembler

Object code

Linker

Executable program

10

Library

Engineering and Information Technology

Syntactical Similarities and Differences main, argc, argv

Advanced C++ for Java


Programmers

Main program function is the entry point of the application:

11

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


Always a function outside of a class
Returns 0 if okay and non-zero otherwise
First argument (argv[0]) contains the name and the
path of the program
Example: /home/mdm3/prg arg1 arg2
This gives the following arguments:

argv[0]:
argv[1]:
argv[2]:
argc:

/home/mdm3/prg
arg1
arg2
3

Engineering and Information Technology

Advanced C++ for Java


Programmers

Syntactical Similarities and Differences Classes in C++ (1)

12

Data members :
Member functions :

Attributes
Methods

Class declaration:
Describe the member functions and the data members of
the class
This is described in .h files (e.g. queue.h)

Class definition:
Contains the code that implements the member functions
This is described in .cpp files (e.g. queue.cpp)

Engineering and Information Technology

Syntactical Similarities and Differences Classes in C++ (2)

Advanced C++ for Java


Programmers

Class declaration

13

Class TagName
{
// class body
};

Class body
Data members
Member functions

Engineering and Information Technology

Syntactical Similarities and Differences Classes in C++ (3)

Advanced C++ for Java


Programmers

Example

14

class IntQueue
{
public:
int size( void );
int isEmpty( void );
int isFull( void );
void enqueue( int elem );
int serve( void );
protected:
int queueSize;
int front;
int rear;
int array[100];
};

Engineering and Information Technology

Syntactical Similarities and Differences Classes in C++ / Access levels

Advanced C++ for Java


Programmers

15

Public member
Accessible from anywhere

Protected member
Behaves as public to a derived class
Behaves as private to the rest

Private member (default access level)


Only accessible by the member functions of its class

Engineering and Information Technology

Syntactical Similarities and Differences Classes in C++ / Class definition

Advanced C++ for Java


Programmers

#include "IntQueue.h

16

int IntQueue::size( void )


{
return queueSize;
}
int IntQueue::isEmpty( void )
{
return queueSize == 0;
}
int IntQueue::isFull( void )
{
return queueSize == 100;
}
void IntQueue::enqueue( int elem )
{
if( ! isFull() ) {
rear = ( ++rear % 100 );
array[ rear ] = elem;
queueSize++;
}
}

int IntQueue::serve( void )


{
if( ! isEmpty() )
{
Object ret = array[front];
front = ( ++front % 100 );
queueSize--;
return ret;
}
else
// exception (see later!)
}

Engineering and Information Technology

Syntactical Similarities and Differences const member functions (1)

Advanced C++ for Java


Programmers

17

Keyword const defines a constant variable (in Java


final)
The attempt to modify a const variable will create a
compiler error
const char blank = ;
blank = x;
compilation error

Class objects can also be const, thus safe and unsafe


member functions exist
const IntQueue queue;
int emtpy = queue.isEmpty();
queue.enqueue (13);

// safe
//unsafe

Engineering and Information Technology

Syntactical Similarities and Differences const member functions (2)

Advanced C++ for Java


Programmers

18

Safe member functions are indicated safe by specifying them


as const
class IntQueue
{
public:
int size( void ) const;
int isEmpty( void ) const;
int isFull( void ) const;
void enqueue( int elem );
int serve();
// .....
};

The const declaration has to be repeated in the


implementation
int IntQueue::isEmpty( void ) const
{
return queueSize == 0;
}

Engineering and Information Technology

Syntactical Similarities and Differences const member functions (3)

Advanced C++ for Java


Programmers

19

It is illegal to declare const a member function that modifies a


data member.
void IntQueue::enqueue( int elem ) const
{
if( ! isFull() )
{
rear = ( ++rear % arraySize );
array[ rear ] = elem;
queueSize++;
}
}

Engineering and Information Technology

Syntactical Similarities and Differences Instantiation and object access (1)

Advanced C++ for Java


Programmers

20

Two different instantiations exist in C++


Static instantiation (automatic allocation and freeing of
memory)
{
IntQueue queue;
// executes constructor
...
queue.enqueue(7);
}
// here, the queue object is destroyed

Java doesnt use the static way, it uses the dynamic


allocation!

Engineering and Information Technology

Advanced C++ for Java


Programmers

Syntactical Similarities and Differences Instantiation and object access (2)


Dynamic instantiation (explicit usage of new and delete).
Java uses the same mechanism. The only exception is
the automatic garbage collector, which doesnt exist in
C++
IntQueue* queuePtr;

// creation of IntQueue pointer

// allocation of memory and execution of the


constructor
queuePtr = new IntQueue();
(*queuePtr).enqueue(13); // dereferencing method
queuePtr->enqueue(13);
// abbreviated method

delete queuePtr; // destructor and freeing of memory

The -> operator dereference an object for function using

21

Engineering and Information Technology

Advanced C++ for Java


Programmers

Syntactical Similarities and Differences Instantiation and object access (3)

22

No garbage collection exists in C++, for this reason, the


programmer is responsible to destroy any dynamically
created objects. The delete (free in Java) command will
be used for this purpose.
The creation and destruction of dynamic arrays looks like
this:
// create an array of 10 IntQueue objects
IntQueue* queues = new IntQueue [10]

// destruct the 10 queues


delete [] queues;

Engineering and Information Technology

Syntactical Similarities and Differences Reference Types (1)

Advanced C++ for Java


Programmers

23

A reference type declares a new symbol for an existing


variable or object
int i = 10;
int& p = i;
int m = p;
int* r = &p;

A reference type must always be initialized


int& q;

// p stands for the same adr as i


// m = 10
// r is a pointer to i
// error, not initialized

In the example above p means the same memory place than i


Reference type should only be used as argument or return
type of functions. (They can be very confusing)

Engineering and Information Technology

Syntactical Similarities and Differences Reference Types (2)

Advanced C++ for Java


Programmers

24

C++ passes arguments by value. Thus, modifications are


made on local copies and the arguments remain untouched
void swap (int

v1, int

v2){...}

Using pointers is a work around


void pswap (int* v1, int* v2){...}
The call would be: pswap(&i, &j);

Another possibility is to use the reference types


void rswap (int& v1, int& v2){...}
The call would be: rswap(i, j);
The reference types are used in the following cases:
When the function arguments have to altered in the function (like
Java)
When large objects have to be passed (time and space costs)

Engineering and Information Technology

Syntactical Similarities and Differences Reference Types (3)

Advanced C++ for Java


Programmers

Reference types can also be used as return type. This avoids


the creation of a copy of a huge object
HugeObj addObjects( HugeObj& l, HugeObj& r){
HugeObj result;
....
return result; // the whole object is copied
}

With a reference type as return type:


HugeObj& addObjects( HugeObj& l, HugeObj& r){
....
return result; // a reference to result is returned
}

The object result must be a data member of the class HugeObj

25

Engineering and Information Technology

Advanced C++ for Java


Programmers

Advanced C++ for Java Programmers

26

New room allocation

Rolex Building, room N321

Still Monday 17h55 19h30

Engineering and Information Technology

Syntactical Similarities and Differences Reference Types - Exercise

Advanced C++ for Java


Programmers

27

Exercise 1-1 (page 10)

Engineering and Information Technology

Syntactical Similarities and Differences This pointer (1)

Advanced C++ for Java


Programmers

28

Any object instance maintains its own copy of the class


data member
But only one copy of the member functions exists
This presents two problems:
As only one instance of a member function exists, it cant
be stored inside the class object instance
How are the particular data members of a class
manipulated within the member function?

The this pointer (similar to the this reference in Java)


can solve this problem
Each class member function contains a pointer of its
class type

Engineering and Information Technology

Syntactical Similarities and Differences This pointer (2)

Advanced C++ for Java


Programmers

29

The member function


void Point::Shift(int dx, int dy)
{
x += dx;
y += dy;
}

Will be internally by the Compiler modified into a nonmember C function like this:
void Shift__Point(Point* this, int dx, int dy)
{
this->x += dx;
this->y += dy;
}

Engineering and Information Technology

Syntactical Similarities and Differences This pointer (3)

Advanced C++ for Java


Programmers

30

Invocation of the member function


myPoint.Shift(2, 3);

Will be translated by the compiler to


Shift__Point(&myPoint, 2, 3);

The programmer can also explicitly reference the this


pointer
bool Point::isEqual(Point& p)
{
if (this == &p) return true; // physical eq
return ((x==p.x)&&(y==p.y));
}

Engineering and Information Technology

Syntactical Similarities and Differences


Static Class Members (1)

Advanced C++ for Java


Programmers

31

All instances of a class have access to the same


variable (e.g. counters, flags, Mutex, ...)
For example a counter of object instances

The same than class methods and class data fields in


Java
This global variable for its class provides two major
advantages over the usage of global variables:
Information hiding (declaring as private)
The static member is not in the programs global name
space (avoids name conflicts)

Engineering and Information Technology

Syntactical Similarities and Differences


Static Class Members (2)

Advanced C++ for Java


Programmers

32

Definition of the single static member in a class with the


keyword static in front of the data type
class TempFile
{
public:
static int nrOfOpenedFiles(void);
private:
static int nrOfFiles;
}

Engineering and Information Technology

Syntactical Similarities and Differences


Static Class Members (3)

Advanced C++ for Java


Programmers

33

The initialization must be done outside the class


definition (like a non-member variable)
Normally done in the definition file (e.g. TempFile.cpp)
The class scope must be used:

int TempFile::nrOfFiles = 0;

A member function that accesses only static members


may be declared also static (see slide before)
Accessing a static data member is like accessing any
other data member.

Engineering and Information Technology

Advanced C++ for Java


Programmers

Syntactical Similarities and Differences


Static Class Members (4)

34

A static member function has no this pointer


A static member and/or a static member function can be
accessed respectively invoked directly (even if no object
of the class exists)
openFiles = TempFile::nrOfOpenedFiles();

Engineering and Information Technology

Syntactical Similarities and Differences


Inline functions (1)

Advanced C++ for Java


Programmers

35

Inline member functions are declared and defined within


its class
Compiler optimization can reduce call overhead of inline
functions, by calling directly the compiled code (inline
expansion)
The inline specifier forces the compiler to try the inline
expansion
Inline requests are reserved for small, frequently used
functions (e.g. operator functions, getter, setter, ...)
Inline functions are used to replace the C-style macros
(e.g. #define max(x, y) ((x > y)? x: y))
Inline functions are type-safe!!! (Not the case of Cstyle macros)

Engineering and Information Technology

Syntactical Similarities and Differences


Inline functions (2)

Advanced C++ for Java


Programmers

36

Examples
class X
{
public:
char* func(void) {return i;}; //inline by default
}
is the same as:
inline char* X::func(void)
{
return i;
}

Engineering and Information Technology

Syntactical Similarities and Differences


Inheritance (1)

Advanced C++ for Java


Programmers

37

In C++ no explicit base class (as in Java the Object


class) exists
Any class that does not have a super class is a base
class
Inheritance should be used in the normal OO way
The syntax:
class subclass : public baseclass
example next slide

Engineering and Information Technology

Advanced C++ for Java


Programmers

Syntactical Similarities and Differences


Inheritance (2)

38

class Vehicle
{
public:
Vehicle();
Vehicle(unsigned int wt);
unsigned int getWeight(void)
const;
void setWeight(unsigned int wt);
private:
unsigned int weight;
};

class LandVehicle : public Vehicle


{
public:
LandVehicle();
LandVehicle(unsigned int wt,
unsigned int sp);
unsigned int getSpeed(void) const;
void setSpeed(unsigned int sp);
private:
unsigned int speed;
};

Engineering and Information Technology

Syntactical Similarities and Differences


Inheritance (3)

Advanced C++ for Java


Programmers

Three inheritance level for the base class exists:

39

Public inheritance The inheritance is part of the


interface
Private inheritance The inheritance is not part of the
interface, it is just an implementation detail
Protected inheritance The inheritance is part of the
interface of the derived class

Engineering and Information Technology

Syntactical Similarities and Differences


Inheritance (4)

Advanced C++ for Java


Programmers

Access specifier in the base class

40

Private

Public

Protected

Public
inheritance

Private
member

Public
member

Protected
member

Private
inheritance

Private
member

Private
member

Private
member

Protected
inheritance

Private
member

Protected
member

Protected
member

Engineering and Information Technology

Advanced C++ for Java


Programmers

Syntactical Similarities and Differences Inheritance


Initialization of a derived classes (1)

41

Different possibilities to initialize a derived class exists


The easy one, where the default constructor of the base
class is used:
LandVehicle::LandVehicle(unsigned int wt, unsigned
int sp)
{
setWeight(wt);
setSpeed(sp);
}

Not very good, because first the default constructor of


Vehicle is called and then the setter method setWeight
This can be done in one single step

Engineering and Information Technology

Syntactical Similarities and Differences Inheritance


Initialization of a derived classes (2)

Advanced C++ for Java


Programmers

42

Not the base classes default constructor will be used,


but its customized one that already sets the weight of
the vehicle.
LandVehicle::LandVehicle(unsigned int wt, unsigned
int sp) : Vehicle(wt), speed(sp)
{
// nothing to do
}

The list of the calls right after the constructer is called


member initialization list
The member initialization list can contain calls to the baseclass constructors as also constructors for class members

Engineering and Information Technology

Syntactical Similarities and Differences


Multiple inheritance

Advanced C++ for Java


Programmers

43

A C++ class can be derived from more than just one


super class (not possible in Java)
The derivation from multiple classes will be specified in
a comma separated list:
class Truck : public Engine, public Trailer
{
...
}

The keyword (public, private or protected) must be


repeated before each base class specification. Of course,
the access levels can be intermixed!

Engineering and Information Technology

Syntactical Similarities and Differences


Polymorphism

Advanced C++ for Java


Programmers

44

The same operation may behave differently on different


classes
E.g. the addition operation on an integer behaves different
as on a complex number

The dynamic binding or late binding decides during runtime which classes operation will be executed
Virtual functions uses the dynamic binding
Without using virtual functions, no dynamic binding will be
performed, even if the pointers are cast to another class
type!

Engineering and Information Technology

Syntactical Similarities and Differences


Polymorphism Virtual functions

Advanced C++ for Java


Programmers

45

Virtual declared functions will cope with the previously


seen problem, that a cast pointer to an object will
execute function of the cast object
The keyword virtual for the common methods must be
used
Only class member functions can be declared as virtual

The redefinition of a virtual function in a derived class


must match exactly the name, signature and return type
of the base class instance
If the redefinition doesnt match exactly, the function is not
handled as virtual for the derived class

Engineering and Information Technology

Syntactical Similarities and Differences


Polymorphism Pure Virtual functions (1)

Advanced C++ for Java


Programmers

46

Pure virtual functions are functions that arent declared


in the base class, because it makes no sense to call the
function on a base class object
The Java correspondence are the abstract method

Any class that declares or inherits a pure virtual function


is a abstract base class
The creation of an object of an abstract base class will
cause a compile error!

A class inheriting from an abstract base class and


overriding an pure virtual function will become a
concrete (non-abstract) class

Engineering and Information Technology

Syntactical Similarities and Differences


Polymorphism Pure Virtual functions (2)

Advanced C++ for Java


Programmers

47

An abstract base class declares an interface


No full set of implementation is needed
Similar to Java interface (interfaces doesnt exist in C++)
The interface specifies the abstract operations of all
derived objects
A pure virtual function is declared with a =0 after the
argument
class Vehicle
{
public:
virtual unsigned int getSpeed(void) = 0;
}

Engineering and Information Technology

Syntactical Similarities and Differences

Advanced C++ for Java


Programmers

48

Exercises that should be checked and that should count


for the bonus must:
be mailed to michael.maeder@bfh.ch
with the Subject: [Exercisex-y]
at latest on Monday after, not after 17h00

S-ar putea să vă placă și