Advanced C++ for Java Programmers

Similar documents
C++ INTERVIEW QUESTIONS

C++ Programming Language

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

The C Programming Language course syllabus associate level

Inheritance in Programming Languages

Glossary of Object Oriented Terms

An Incomplete C++ Primer. University of Wyoming MA 5310

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Description of Class Mutation Mutation Operators for Java

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

Sources: On the Web: Slides will be available on:

Object Oriented Software Design II

CORBA Programming with TAOX11. The C++11 CORBA Implementation

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Java Interview Questions and Answers

Comp151. Definitions & Declarations

El Dorado Union High School District Educational Services

Konzepte objektorientierter Programmierung

On the (un)suitability of Java to be the first programming language

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang

Classes and Pointers: Some Peculiarities (cont d.)

1. Polymorphism in C++...2

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

1.1.3 Syntax The syntax for creating a derived class is very simple. (You will wish everything else about it were so simple though.

Evolution of the Major Programming Languages

13 Classes & Objects with Constructors/Destructors

Habanero Extreme Scale Software Research Project

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

C++FA 5.1 PRACTICE MID-TERM EXAM

BCS2B02: OOP Concepts and Data Structures Using C++

CSC230 Getting Starting in C. Tyler Bletsch

CEC225 COURSE COMPACT

OpenCL Static C++ Kernel Language Extension

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Fundamentals of Java Programming

A deeper look at Inline functions

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

CIS 190: C/C++ Programming. Polymorphism

Lecture 1: Introduction

Chapter 1 Fundamentals of Java Programming

Moving from CS 61A Scheme to CS 61B Java

Advanced Data Structures

Basic Logic Gates. Logic Gates. andgate: accepts two binary inputs x and y, emits x & y. orgate: accepts two binary inputs x and y, emits x y

Object Oriented Software Design II

An Introduction to Assembly Programming with the ARM 32-bit Processor Family

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Crash Course in Java

Object Oriented Programming With C++(10CS36) Question Bank. UNIT 1: Introduction to C++

Compile-time type versus run-time type. Consider the parameter to this function:

Java Programming Language

Semantic Analysis: Types and Type Checking

History OOP languages Year Language 1967 Simula Smalltalk

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Basics of C++ and object orientation in OpenFOAM

CSE 307: Principles of Programming Languages

Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance

Java Application Developer Certificate Program Competencies

Object-Oriented Programming

C++ Support for Abstract Data Types

CS11 Advanced C++ Spring Lecture 9 (!!!)

1 Abstract Data Types Information Hiding

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Tutorial on Writing Modular Programs in Scala

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

CS 111 Classes I 1. Software Organization View to this point:

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Java CPD (I) Frans Coenen Department of Computer Science

Object Oriented Software Design II

Objectif. Participant. Prérequis. Remarque. Programme. C# 3.0 Programming in the.net Framework. 1. Introduction to the.

ECE 122. Engineering Problem Solving with Java

Laboratory Assignments of OBJECT ORIENTED METHODOLOGY & PROGRAMMING (USING C++) [IT 553]

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

Basic Object-Oriented Programming in Java

Friendship and Encapsulation in C++

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

Parameter Passing. Parameter Passing. Parameter Passing Modes in Fortran. Parameter Passing Modes in C

1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) {

Grundlagen der Betriebssystemprogrammierung

Java from a C perspective. Plan

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

AP Computer Science Java Subset

Introduction to Objective-C. Kevin Cathey

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Managing Variability in Software Architectures 1 Felix Bachmann*

Chapter 5 Names, Bindings, Type Checking, and Scopes

5 Arrays and Pointers

Getting Started with the Internet Communications Engine

Informatica e Sistemi in Tempo Reale

Organization of Programming Languages CS320/520N. Lecture 05. Razvan C. Bunescu School of Electrical Engineering and Computer Science

Copyright 2001, Bill Trudell. Permission is granted to copy for the PLoP 2001 conference. All other rights reserved.

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

WORKSPACE WEB DEVELOPMENT & OUTSOURCING TRAINING CENTER

Adapter, Bridge, and Façade

Transcription:

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

Semester organisation Theoretical lecture with practical hands-on. Two exams (will be announced) Homework (optional, bonus for end grade) Eventually a Mini-Project 2

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 3

Information and Bibliography (printed at the school s 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, O Reilly Practical C++ Programming, Steve Oualline, O Reilly... and a lot more 4

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

Major reasons for Java 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 6

Differences and Similarities

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

Contribution of other languages to Java Simula 9 Ada Sm alltalk C Pascal Eiffel Objective-C C++ Java Object- Pascal Oberon-2 Modula-2 Modula-3

Transformation from a C++ source code to an executable program High-level code C++ source code Compiler Assembly-language program Assembler Object code Linker Library 10 Executable program

Syntactical Similarities and Differences - main, argc, argv Main program function is the entry point of the application: 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]: /home/mdm3/prg argv[1]: arg1 argv[2]: arg2 argc: 3 11

Syntactical Similarities and Differences - Classes in C++ (1) 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) 12

Syntactical Similarities and Differences - Classes in C++ (2) Class declaration Class TagName // class body }; Class body Data members Member functions 13

Syntactical Similarities and Differences - Classes in C++ (3) Example 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]; }; 14

Syntactical Similarities and Differences - Classes in C++ / Access levels 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 15

Syntactical Similarities and Differences - Classes in C++ / Class definition #include "IntQueue.h 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!) } 16

Syntactical Similarities and Differences - const member functions (1) 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 17

Syntactical Similarities and Differences - const member functions (2) 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; } 18

Syntactical Similarities and Differences - const member functions (3) 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++; } } 19

Syntactical Similarities and Differences - Instantiation and object access (1) 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 doesn t use the static way, it uses the dynamic allocation! 20

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

Syntactical Similarities and Differences - Instantiation and object access (3) 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; 22

Syntactical Similarities and Differences - Reference Types (1) A reference type declares a new symbol for an existing variable or object int i = 10; int& p = i; // p stands for the same adr as i int m = p; // m = 10 int* r = &p; // r is a pointer to i A reference type must always be initialized int& q; // 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) 23

Syntactical Similarities and Differences - Reference Types (2) 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) 24

Syntactical Similarities and Differences - Reference Types (3) 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

New room allocation Rolex Building, room N321 Still Monday 17h55 19h30 26

Syntactical Similarities and Differences - Reference Types - Exercise Exercise 1-1 (page 10) 27

Syntactical Similarities and Differences - This pointer (1) 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 can t 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 28

Syntactical Similarities and Differences - This pointer (2) 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; 29

Syntactical Similarities and Differences - This pointer (3) 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)); } 30

Syntactical Similarities and Differences Static Class Members (1) 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 program s global name space (avoids name conflicts) 31

Syntactical Similarities and Differences Static Class Members (2) 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; } 32

Syntactical Similarities and Differences Static Class Members (3) 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. 33

Syntactical Similarities and Differences Static Class Members (4) 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(); 34

Syntactical Similarities and Differences Inline functions (1) 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 C- style macros) 35

Syntactical Similarities and Differences Inline functions (2) Examples class X public: char* func(void) return i;}; //inline by default } is the same as: inline char* X::func(void) return i; } 36

Syntactical Similarities and Differences Inheritance (1) 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 37

Syntactical Similarities and Differences Inheritance (2) 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; }; 38

Syntactical Similarities and Differences Inheritance (3) Three inheritance level for the base class exists: 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 39

Syntactical Similarities and Differences Inheritance (4) Access specifier in the base class Public inheritance Private inheritance Protected inheritance Private Private member Private member Private member Public Public member Private member Protected member Protected Protected member Private member Protected member 40

Syntactical Similarities and Differences Inheritance Initialization of a derived classes (1) 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 41

Syntactical Similarities and Differences Inheritance Initialization of a derived classes (2) Not the base classe s 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 42

Syntactical Similarities and Differences Multiple inheritance 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! 43

Syntactical Similarities and Differences Polymorphism 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! 44

Syntactical Similarities and Differences Polymorphism Virtual functions 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 doesn t match exactly, the function is not handled as virtual for the derived class 45

Syntactical Similarities and Differences Polymorphism Pure Virtual functions (1) Pure virtual functions are functions that aren t 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 46

Syntactical Similarities and Differences Polymorphism Pure Virtual functions (2) An abstract base class declares an interface No full set of implementation is needed Similar to Java interface (interfaces doesn t 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; } 47

Syntactical Similarities and Differences 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 48