C++ Crash Kurs. C++ Object-Oriented Programming

Size: px
Start display at page:

Download "C++ Crash Kurs. C++ Object-Oriented Programming"

Transcription

1 C++ Crash Kurs C++ Object-Oriented Programming Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

2 C++ classes A class is user-defined type encapsulating data and operations on that data Example Data of a Point might be int x, y; Operations may be move, draw, Class operations are often called methods or member functions A class offers the ability to be cleanly initialized (using constructors) and destroyed (using destructors) 2

3 Notation: Classes and Objects (Instances) Class Defines the structure and behavior Attributes of a class form the structure Methods define the behavior Lamp brighter(); darker(); Object or Instance Called the realization of a class Has an identity (this-pointer) Owns a separate set of attributes (state) State changes through method invocation int brightness; l 1 ; Analogy Car vs. My BMW Human vs. me l n ; 3

4 Declaring classes Declaration similar to struct s class Name <access-control> <data-member> <method/function> repeat as often as necessary Access control for methods and attributes public: For anybody private: Only within this class protected: Within this class and within sub-classes Most data should be private while most functions public 4

5 Declaring classes class MyClassName public: int method1(); void another_one(); private: void secret_one(); Ok. However, it is good practice to have only one private, protected and public block public: void another_public_one(); protected: void only_visible_to_inherited(); int my_protected_state; Don t forget the ; as this will cause strange compiler errors 5

6 C++ class vs. C struct Key word class instead of struct Struct and Class are interchangeable struct s now may also have methods struct: public is standard access level class: private is standard access level Good practice: Always use class in C++ struct x void f(); //public struct x public: void f(); 1:1 class x void f(); //private class x public: void f(); 6

7 Using classes A class can be used just like any other type Instances are defined just like predefined type instances Methods are invoked via variable_name.method_identifier Instances may be assigned, passed as arguments, and returned by functions Example (assignment) Point p1, p2; p1.set( 1, 3); p2 = p1; Automatic element-wise copy (just like with struct) i.e., p2.x = p1.x; p2.y = p1.y; 7

8 Using classes //File: point.h class Point public: set(int x, int y); move(int dx, int dy); int x(); int y(); private: int x_; int y_; #include point.h #include <iostream> using namespace std; int main(int argc, char** argv) Point p; p.set( 1, 3 ); cout << p( << p.x() <<, << p.y() << ) << endl; } p.move( 10, 10 ); cout << p( << p.x() <<, << p.y() << ) << endl; 8

9 Initializing classes How to ensure a correct (i.e., predetermined) startup state Constructors Member initialization lists Constructors Member functions called just like the class itself Have no return value Invoked whenever a class instance is allocated Constructor overloading is allowed Member initialization lists Used instead of value assignments to members in constructors Must be used to parameterize constructors of base classes 9

10 Constructors Constructor invoked on object instantiation Example Point p; Point p(1,2); Every class should have a constructor //File: point.h class Point public: Point() x_=0; y_=0; } Point(int ax, int ay) x_ = ax; y_ = ay; } set(int x, int y); move(int dx, int dy); int x(); int y(); private: int x_; int y_; 10

11 Constructors Constructors can not be invoked like normal methods Point p; p.point(); Compiler error A constructor can be used to create new objects Point p; p.set(10, 10); p = Point(100, 100); Point() constructs a temporary instance, which is then assigned to p The temporary instance is popped automatically from the stack at the end of the statement 11

12 Member initialization lists Used instead of value assignments to members in constructors Provides a more objectoriented style Data member are passed arguments to initialize themselves Should be used for (most) members Must be used to parameterize constructors of base classes Point() x_=0; y_=0; } Point(int ax, int ay) x_ = ax; y_ = ay; } Point() : x_(0), y_(0) } Point(int ax, int ay) : x_(ax), y_(ay) } 12

13 Copy-constructor Used to assign one object to another Signature: Classname(const Classname& other); const is not mandatory, yet often sensible If no copy-constructor is implemented Default copy-constructor generated by the compiler Creates 1:1 (shallow) copy of the other object Problem: Pointers are copied as well, not their pointed-at objects More complex objects should implement a copy constructor 13

14 Destructors Counterpart to the constructors Invoked immediately before an object is removed from memory Declaration just like a constructor with leading ~ No overloading possible, no parameters, no return value Perform possibly necessary cleanup Free reserved memory Close open files, network connections, etc. Example class Lamp public: ~Lamp(); 14

15 Implementing methods Methods are functions in classes <modifier> <type> method-name(<parameter list>); Overloading of methods allowed Instances have an identity Pre-defined this -pointer to itself Not available in static members 15

16 Implementing methods: Inline class Lamp public: Lamp() : on_(false), brightness_(10) } void on() on_ = true; } private: bool on_; int brightness_;.h File 16

17 Implementing methods: Separate.cpp File class Lamp public:.h File.cpp File Lamp(); void on(); private: bool on_; int brightness_; #include lamp.h // Lamp:: Lamp() : on_(false), brightness_(10) } // void Lamp::on() on_ = true; } 17

18 Implementing methods: const methods Constant methods May not modify attributes nor call non-const methods Only const-methods may be invoked on const instances <type> method-name(<parameter list>) const; Example class Lamp public: int brightness() const return brightness; } 18

19 Implementing methods: static members Static methods and attributes One instance per class, not per object Can only access other static elements Data elements must be explicitly defined No this pointer available class X public: static void f() static int i; int X::i = 0; void X::f() } X::f(); X::i; 19

20 C++ class access control Access control is classnot instance-specific Private & protected limit access of others Instances of the same class have access to private members of any other instance class A public: void change(a& other) other.i = 10; } private: int i; A a, b; a.change(b); 20

21 C++ class access control: friends Selectively disables access control of a class friend method-signature; or friend class class-name; friends have full access to private/protected members Example x.h y.h #include y.h class X private: void f(); int x; friend void my_friend(); void my_friend(); y.cpp void my_friend() X x; x.f(); x.x = 19; } 21

22 Implicit type conversion using Constructors C++ performs implicit (safe) type conversions E.g., float x = 1; // Conversion from int to float C++ implicit type conversions extended to classes Implicit conversion using constructors or (global) functions Example class A public: A () } class B public: B(const A&) } void f(b b) } int main() A a; f(a); // Wants B, has A } 22

23 Preventing constructor conversion Automatic conversion sometimes not desired May introduce performance problems (many constructor calls) Implicit conversion are not obvious to others reading the code Use explicit modifier to make implicit conversions explicit only Conversion must be made explicit by invoking the conversion constructor Example class A public: A () } class B public: explicit B(const A&) } void f(b b) } int main() A a; f( B( a ) ); // Explicit conversion from A to B } 23

24 Demo C++ Stack class 24

25 Operator Overloading

26 C++ class: Operator overloading Example class Vector public: Vector(float x = 0.0, float y=0.0) : x_(x), y_(y) } float x() const return x_; } float y() const return y_; } private: float x; float y; Vector add(const Vector& a, const Vector& b) return Vector( a.x() + b.x(), a.y() + b.y() ); } Vector a, b, c; a = add( b, c); Goal: Simpler syntax using a = b + c Assign new semantics to operators for custom data types 26

27 C++ class: Operator overloading Assign new semantics to operators for custom data types Key word operator Eye-candy, same functionality can be achieved using method calls Variants Method of a class Normal or friend function Overloadable operators new + % ~ > /= = <<= >= -- () delete - ^! += %= << == &&, [] new[] * & = -= ^= >>!= -> * delete[] / < *= &= >>= <= ++ -> 27

28 Operator overloading: Using methods Definition like normal methods of a class Only the identifier is special OperatorX: X is an operator, e.g. + Example (binary operator+) class Vector Vector operator+(const Vector& other) return Vector( x_ + other.x_, y_ + other.y_); } Usage Vector x, a, b; x = a + b; x = a.operator+(b); 28

29 Operator overloading: Using methods Example (unary operator-) class Vector } Vector operator-() return Vector( -x_, -y_); Usage Vector a(1,1); a = -a; (-1,-1) a = a.operator-(); 29

30 Operator overloading: Using (friend) functions Definition like a normal Function Only the identifier is special is an operator, e.g. +) Example (friend function for binary operator +) class Vector friend friend Vector operator+ (const Vector& a, const Vector& b); Vector operator+ (const Vector& a, const Vector& b) Vector res; res.x = a.x + b.x; res.y = a.y + b.y; return res; } Usage Vector a, b, c; a = b + c; a = operator+ (b, c); 30

31 Operator overloading: Using (friend) functions Example (friend function for unary operator -) class Vector friend Vector operator- (const Vector& v); Vector operator- (const Vector& v) return Vector(-v.x, -v.y); } Usage Vector a, b; b = -a; b = operator-(a); 31

32 Operator overloading: Demo Demo C++ Fraction class 32

33 Operator overloading: Parameters & return values/types Arguments and return values are arbitrary However, there is a useful pattern to follow Typical assumptions Arithmetic operations (like + and, ) do not change their arguments Operator-assignments (like +=) and assignment (=) change the lefthand argument Logical operators do not change their arguments Operations are chainable (e.g., a = b + d * e) 33

34 Operator overloading: Parameters & return values/types Arithmetic operations (like + and, ) do not change their arguments Logical operators (like <, >=,!=) do not modify the operands Rule Arguments that are not changed are passed as const references Member functions are flagged const Example (friend function) const A operator+(const A& left, const A& right); bool operator>(const A& left, const A& right); Example (method) class A const A operator+(const A& right) const; bool operator>(const A& right) const; } 34

35 Operator overloading: Parameters & return values/types Operator-assignments (like +=) and assignment (=) change the left-hand argument Rule Remove const from arguments that are about to be modified Example (friend function) A& operator+=(a& left, const A& right); Example (method) class A A& operator+=(const A& right); } 35

36 Operator overloading: Parameters & return values/types Return value depends on the meaning of the operator If it produces a new value (e.g, +), return a const temporary object so that the result can not be used as an lvalue class A int i; const A operator+ (const A&other) return A( i += other.i ); } } If it modifies the current value, return a (const) reference so that the operator can be chained class A int i; A& operator+=(const A&other) i += other.i; } } return *this; 36

37 Operator overloading: Return optimization Why NOT use A tmp(1); return a;? Using this prevents the compiler from performing return optimization A tmp(1); return tmp; 1. Temporary tmp object is created including constructor call 2. Copy-constructor copies tmp to return location on the stack 3. Destructor is called for tmp at the end of the scope return A(1); Tells the compiler that this temporary is only intended a return value Object is directly created on the stack Optimized performance using constructor call instead of temporary object 37

38 Operator overloading: Distinguish post- and prefix Problem: Both ++x and x++ would be operator++ C++ workaround Use a dummy int parameter for the postfix operator No value or semantics, only provides a different method signature Example class Vector public: Vector operator++(); //Prefix Vector operator++(int); //Postfix Usage (prefix) ++x; x.operator++(); Usage (postfix) x++ x.operator++(0); 38

39 Operator overloading: Methods or (friend) functions? If possible, prefer implementing as a method Always possible if the left operand is the class itself (Friend) functions mandatory when left operand is not the class itself Example class A private: int i; friend ostream& operator<<(ostream& os, const A& a); A a; cout << a= << a << endl; operator<<(cout, a); // Same as above: left operand is of type ostream ostream& operator<<(ostream& os, const A& a) os << a.i; return os; } 39

40 Operator overloading: Methods or (friend) functions? Recommendation Operator Recommended use All unary operators Member = () [] > >* Must be member += = /= *= ^= &= = %= >>= <<= All other binary operators Member (Friend) function [1] Rob Murray, C++ Strategies & Tactics, Addison-Wesley, 1993, page

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example Operator Overloading Lecture 8 Operator Overloading C++ feature that allows implementer-defined classes to specify class-specific function for operators Benefits allows classes to provide natural semantics

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

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

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement? 1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members

More information

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing CpSc212 Goddard Notes Chapter 6 Yet More on Classes We discuss the problems of comparing, copying, passing, outputting, and destructing objects. 6.1 Object Storage, Allocation and Destructors Some objects

More information

Comp151. Definitions & Declarations

Comp151. Definitions & Declarations Comp151 Definitions & Declarations Example: Definition /* reverse_printcpp */ #include #include using namespace std; int global_var = 23; // global variable definition void reverse_print(const

More information

C++ Overloading, Constructors, Assignment operator

C++ Overloading, Constructors, Assignment operator C++ Overloading, Constructors, Assignment operator 1 Overloading Before looking at the initialization of objects in C++ with constructors, we need to understand what function overloading is In C, two functions

More information

C++ INTERVIEW QUESTIONS

C++ INTERVIEW QUESTIONS C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get

More information

Basics of C++ and object orientation in OpenFOAM

Basics of C++ and object orientation in OpenFOAM Basics of C++ and object orientation in OpenFOAM To begin with: The aim of this part of the course is not to teach all of C++, but to give a short introduction that is useful when trying to understand

More information

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

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas CS 110B - Rule Storage Classes Page 18-1 Attributes are distinctive features of a variable. Data type, int or double for example, is an attribute. Storage class is another attribute. There are four storage

More information

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

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

C++FA 5.1 PRACTICE MID-TERM EXAM

C++FA 5.1 PRACTICE MID-TERM EXAM C++FA 5.1 PRACTICE MID-TERM EXAM This practicemid-term exam covers sections C++FA 1.1 through C++FA 1.4 of C++ with Financial Applications by Ben Van Vliet, available at www.benvanvliet.net. 1.) A pointer

More information

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

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) { Operators C and C++ 6. Operators Inheritance Virtual Alastair R. Beresford University of Cambridge Lent Term 2008 C++ allows the programmer to overload the built-in operators For example, a new test for

More information

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

IS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction IS0020 Program Design and Software Tools Midterm, Feb 24, 2004 Name: Instruction There are two parts in this test. The first part contains 50 questions worth 80 points. The second part constitutes 20 points

More information

More C++ Concepts. Operator overloading Friend Function This Operator Inline Function

More C++ Concepts. Operator overloading Friend Function This Operator Inline Function More C++ Concepts Operator overloading Friend Function This Operator Inline Function 1 Review There are different types of member functions in the definition of a class Accessor int Str :: get_length();

More information

13 Classes & Objects with Constructors/Destructors

13 Classes & Objects with Constructors/Destructors 13 Classes & Objects with Constructors/Destructors 13.1 Introduction In object oriented programming, the emphasis is on data rather than function. Class is a way that binds the data & function together.

More information

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority) Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

More information

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

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1 Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1 Introduction to Classes Classes as user-defined types We have seen that C++ provides a fairly large set of built-in types. e.g

More information

N3458: Simple Database Integration in C++11

N3458: Simple Database Integration in C++11 N3458: Simple Database Integration in C++11 Thomas Neumann Technische Univeristät München neumann@in.tum.de 2012-10-22 Many applications make use of relational database to store and query their data. However,

More information

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator= CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator= We already know that the compiler will supply a default (zero-argument) constructor if the programmer does not specify one.

More information

The C Programming Language course syllabus associate level

The C Programming Language course syllabus associate level TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College November 25, 2015 Outline Outline 1 Chapter 12: C++ Templates Outline Chapter 12: C++ Templates 1 Chapter 12: C++ Templates

More information

Ch 7-1. Object-Oriented Programming and Classes

Ch 7-1. Object-Oriented Programming and Classes 2014-1 Ch 7-1. Object-Oriented Programming and Classes May 10, 2014 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel : +82-53-810-2497;

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II C++ intro Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 26, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26,

More information

C++FA 3.1 OPTIMIZING C++

C++FA 3.1 OPTIMIZING C++ C++FA 3.1 OPTIMIZING C++ Ben Van Vliet Measuring Performance Performance can be measured and judged in different ways execution time, memory usage, error count, ease of use and trade offs usually have

More information

explicit class and default definitions revision of SC22/WG21/N1582 = 04-0022 and SC22/WG21/ N1702 04-0142

explicit class and default definitions revision of SC22/WG21/N1582 = 04-0022 and SC22/WG21/ N1702 04-0142 Doc No: SC22/WG21/ N1717 04-0157 Project: Programming Language C++ Date: Friday, November 5, 2004 Author: Francis Glassborow & Lois Goldthwaite email: francis@robinton.demon.co.uk explicit class and default

More information

Goals for This Lecture:

Goals for This Lecture: Goals for This Lecture: Understand the pass-by-value and passby-reference argument passing mechanisms of C++ Understand the use of C++ arrays Understand how arrays are passed to C++ functions Call-by-value

More information

Functions and Parameter Passing

Functions and Parameter Passing Chapter 5: Functions and Parameter Passing In this chapter, we examine the difference between function calls in C and C++ and the resulting difference in the way functions are defined in the two languages.

More information

A Summary of Operator Overloading

A Summary of Operator Overloading A Summary of Operator Overloading David Kieras, EECS Dept., Univ. of Michigan Prepared for EECS 381 8/27/2013 Basic Idea You overload an operator in C++ by defining a function for the operator. Every operator

More information

El Dorado Union High School District Educational Services

El Dorado Union High School District Educational Services El Dorado Union High School District Course of Study Information Page Course Title: ACE Computer Programming II (#495) Rationale: A continuum of courses, including advanced classes in technology is needed.

More information

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

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 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 preceded by an equal sign d. its name has undereline 2. Associations

More information

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

More information

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

Copyright 2001, Bill Trudell. Permission is granted to copy for the PLoP 2001 conference. All other rights reserved. The Secret Partner Pattern Revision 3a by Bill Trudell, July 23, 2001 Submitted to the Pattern Languages of Programs Shepherd: Neil Harrison PC Member: Kyle Brown Thumbnail This paper describes the Secret

More information

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

An Incomplete C++ Primer. University of Wyoming MA 5310 An Incomplete C++ Primer University of Wyoming MA 5310 Professor Craig C. Douglas http://www.mgnet.org/~douglas/classes/na-sc/notes/c++primer.pdf C++ is a legacy programming language, as is other languages

More information

Syllabus OBJECT ORIENTED PROGRAMMING C++

Syllabus OBJECT ORIENTED PROGRAMMING C++ 1 Syllabus OBJECT ORIENTED PROGRAMMING C++ 1. Introduction : What is object oriented programming? Why do we need objectoriented. Programming characteristics of object-oriented languages. C and C++. 2.

More information

Applied Informatics C++ Coding Style Guide

Applied Informatics C++ Coding Style Guide C++ Coding Style Guide Rules and Recommendations Version 1.4 Purpose of This Document This document describes the C++ coding style employed by Applied Informatics. The document is targeted at developers

More information

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

Object Oriented Programming With C++(10CS36) Question Bank. UNIT 1: Introduction to C++ Question Bank UNIT 1: Introduction to C++ 1. What is Procedure-oriented Programming System? Dec 2005 2. What is Object-oriented Programming System? June 2006 3. Explain the console I/O functions supported

More information

Glossary of Object Oriented Terms

Glossary of Object Oriented Terms Appendix E Glossary of Object Oriented Terms abstract class: A class primarily intended to define an instance, but can not be instantiated without additional methods. abstract data type: An abstraction

More information

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

KITES TECHNOLOGY COURSE MODULE (C, C++, DS) KITES TECHNOLOGY 360 Degree Solution www.kitestechnology.com/academy.php info@kitestechnology.com technologykites@gmail.com Contact: - 8961334776 9433759247 9830639522.NET JAVA WEB DESIGN PHP SQL, PL/SQL

More information

CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator=

CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator= CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator= Much of the surrounding prose written by Andy Maag, CS193D instructor from years ago. The compiler will supply a default (zero-argument)

More information

Function Overloading I

Function Overloading I Function Overloading I we can overload functions on their arguments like so: void foo (int iarg) { cout

More information

Course notes Standard C++ programming

Course notes Standard C++ programming Department of Cybernetics The University of Reading SE2B2 Further Computer Systems Course notes Standard C++ programming by Dr Virginie F. Ruiz November, 03 CREATING AND USING A COPY CONSTRUCTOR... 27

More information

Chapter 5 Functions. Introducing Functions

Chapter 5 Functions. Introducing Functions Chapter 5 Functions 1 Introducing Functions A function is a collection of statements that are grouped together to perform an operation Define a function Invoke a funciton return value type method name

More information

Introduction to Programming Block Tutorial C/C++

Introduction to Programming Block Tutorial C/C++ Michael Bader Master s Program Computational Science and Engineering C/C++ Tutorial Overview From Maple to C Variables, Operators, Statements Functions: declaration, definition, parameters Arrays and Pointers

More information

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

CORBA Programming with TAOX11. The C++11 CORBA Implementation CORBA Programming with TAOX11 The C++11 CORBA Implementation TAOX11: the CORBA Implementation by Remedy IT TAOX11 simplifies development of CORBA based applications IDL to C++11 language mapping is easy

More information

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

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London

More information

Constructor, Destructor, Accessibility and Virtual Functions

Constructor, Destructor, Accessibility and Virtual Functions Constructor, Destructor, Accessibility and Virtual Functions 182.132 VL Objektorientierte Programmierung Raimund Kirner Mitwirkung an Folienerstellung: Astrit Ademaj Agenda Constructor Destructors this

More information

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

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism Polymorphism Problems with switch statement Programmer may forget to test all possible cases in a switch. Tracking this down can be time consuming and error prone Solution - use virtual functions (polymorphism)

More information

Subject Name: Object Oriented Programming in C++ Subject Code: 2140705

Subject Name: Object Oriented Programming in C++ Subject Code: 2140705 Faculties: L.J. Institute of Engineering & Technology Semester: IV (2016) Subject Name: Object Oriented Programming in C++ Subject Code: 21405 Sr No UNIT - 1 : CONCEPTS OF OOCP Topics -Introduction OOCP,

More information

Advanced Data Structures

Advanced Data Structures C++ Advanced Data Structures Chapter 8: Advanced C++ Topics Zhijiang Dong Dept. of Computer Science Middle Tennessee State University Chapter 8: Advanced C++ Topics C++ 1 C++ Syntax of 2 Chapter 8: Advanced

More information

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference? Functions in C++ Let s take a look at an example declaration: Lecture 2 long factorial(int n) Functions The declaration above has the following meaning: The return type is long That means the function

More information

Java Interview Questions and Answers

Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

More information

C++ Support for Abstract Data Types

C++ Support for Abstract Data Types Topics C++ Support for Abstract Data Types Professor Department of EECS d.schmidt@vanderbilt.edu Vanderbilt University www.cs.wustl.edu/schmidt/ (615) 343-8197 Describing Objects Using ADTs Built-in vs.

More information

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

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies) Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies) Duration of Course: 6 Months Fees: Rs. 25,000/- (including Service Tax) Eligibility: B.E./B.Tech., M.Sc.(IT/ computer

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Real Application Design Christian Nastasi http://retis.sssup.it/~lipari http://retis.sssup.it/~chris/cpp Scuola Superiore Sant Anna Pisa April 25, 2012 C. Nastasi (Scuola

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming Programming with Data Types to enhance reliability and productivity (through reuse and by facilitating evolution) Object (instance) State (fields) Behavior (methods) Identity

More information

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

More information

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

An Introduction to Assembly Programming with the ARM 32-bit Processor Family An Introduction to Assembly Programming with the ARM 32-bit Processor Family G. Agosta Politecnico di Milano December 3, 2011 Contents 1 Introduction 1 1.1 Prerequisites............................. 2

More information

Semantic Analysis: Types and Type Checking

Semantic Analysis: Types and Type Checking Semantic Analysis Semantic Analysis: Types and Type Checking CS 471 October 10, 2007 Source code Lexical Analysis tokens Syntactic Analysis AST Semantic Analysis AST Intermediate Code Gen lexical errors

More information

www.sahajsolns.com Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

www.sahajsolns.com Chapter 4 OOPS WITH C++ Sahaj Computer Solutions Chapter 4 OOPS WITH C++ Sahaj Computer Solutions 1 Session Objectives Classes and Objects Class Declaration Class Members Data Constructors Destructors Member Functions Class Member Visibility Private,

More information

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system. http://www.tutorialspoint.com/java/java_quick_guide.htm JAVA - QUICK GUIDE Copyright tutorialspoint.com What is Java? Java is: Object Oriented Platform independent: Simple Secure Architectural- neutral

More information

Binary storage of graphs and related data

Binary storage of graphs and related data EÖTVÖS LORÁND UNIVERSITY Faculty of Informatics Department of Algorithms and their Applications Binary storage of graphs and related data BSc thesis Author: Frantisek Csajka full-time student Informatics

More information

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure Short Notes on Dynamic Memory Allocation, Pointer and Data Structure 1 Dynamic Memory Allocation in C/C++ Motivation /* a[100] vs. *b or *c */ Func(int array_size) double k, a[100], *b, *c; b = (double

More information

Moving from C++ to VBA

Moving from C++ to VBA Introduction College of Engineering and Computer Science Mechanical Engineering Department Mechanical Engineering 309 Numerical Analysis of Engineering Systems Fall 2014 Number: 15237 Instructor: Larry

More information

C++ program structure Variable Declarations

C++ program structure Variable Declarations C++ program structure A C++ program consists of Declarations of global types, variables, and functions. The scope of globally defined types, variables, and functions is limited to the file in which they

More information

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions Phys4051: C Lecture 2 & 3 Functions (Review) Comment Statements Variables & Operators Branching Instructions Comment Statements! Method 1: /* */! Method 2: // /* Single Line */ //Single Line /* This comment

More information

EP241 Computer Programming

EP241 Computer Programming EP241 Computer Programming Topic 10 Basic Classes Department of Engineering Physics University of Gaziantep Course web page www.gantep.edu.tr/~bingul/ep241 Sep 2013 Sayfa 1 Introduction In this lecture

More information

Brent A. Perdue. July 15, 2009

Brent A. Perdue. July 15, 2009 Title Page Object-Oriented Programming, Writing Classes, and Creating Libraries and Applications Brent A. Perdue ROOT @ TUNL July 15, 2009 B. A. Perdue (TUNL) OOP, Classes, Libraries, Applications July

More information

COMPUTER SCIENCE 1999 (Delhi Board)

COMPUTER SCIENCE 1999 (Delhi Board) COMPUTER SCIENCE 1999 (Delhi Board) Time allowed: 3 hours Max. Marks: 70 Instructions: (i) All the questions are compulsory. (ii) Programming Language: C++ QUESTION l. (a) Why main function is special?

More information

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c Lecture 3 Data structures arrays structs C strings: array of chars Arrays as parameters to functions Multiple subscripted arrays Structs as parameters to functions Default arguments Inline functions Redirection

More information

! " # $ %& %' ( ) ) *%%+, -..*/ *%%+ - 0 ) 1 2 1

!  # $ %& %' ( ) ) *%%+, -..*/ *%%+ - 0 ) 1 2 1 !" #$%&%'())*%%+,-..*/*%%+- 0 )12 1 *!" 34 5 6 * #& ) 7 8 5)# 97&)8 5)# 9 : & ; < 5 11 8 1 5)=19 7 19 : 0 5)=1 ) & & >) ) >) 1? 5)= 19 7 19 : # )! #"&@)1 # )? 1 1#& 5)=19719:# 1 5)=9 7 9 : 11 0 #) 5 A

More information

CS107L Handout 04 Autumn 2007 October 19, 2007 Custom STL-Like Containers and Iterators

CS107L Handout 04 Autumn 2007 October 19, 2007 Custom STL-Like Containers and Iterators CS107L Handout 04 Autumn 2007 October 19, 2007 Custom STL-Like Containers and Iterators This handout is designed to provide a better understanding of how one should write template code and architect iterators

More information

Keil C51 Cross Compiler

Keil C51 Cross Compiler Keil C51 Cross Compiler ANSI C Compiler Generates fast compact code for the 8051 and it s derivatives Advantages of C over Assembler Do not need to know the microcontroller instruction set Register allocation

More information

OpenCL Static C++ Kernel Language Extension

OpenCL Static C++ Kernel Language Extension OpenCL Static C++ Kernel Language Extension Document Revision: 04 Advanced Micro Devices Authors: Ofer Rosenberg, Benedict R. Gaster, Bixia Zheng, Irina Lipov December 15, 2011 Contents 1 Overview... 3

More information

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java

More information

Fortgeschrittene Programmierung in C++ Vorbesprechung & 1. Vorlesung

Fortgeschrittene Programmierung in C++ Vorbesprechung & 1. Vorlesung Fortgeschrittene Programmierung in C++ Vorbesprechung & 1. Vorlesung Thomas Gschwind 2013 IBM Corporation Overview Administrative Issues Prerequisites & Goals Schedule Exams & Grading

More information

The C++ Programming Language Single and Multiple Inheritance in C++ Douglas C. Schmidt www.cs.wustl.edu/schmidt/ schmidt@cs.wustl.edu Washington University, St. Louis 1 Background Object-oriented programming

More information

How to: Use Basic C++, Syntax and Operators

How to: Use Basic C++, Syntax and Operators June 7, 1999 10:10 owltex Sheet number 22 Page number 705 magenta black How to: Use Basic C++, Syntax and Operators A In this How to we summarize the basic syntax of C++ and the rules and operators that

More information

C++ Language Tutorial

C++ Language Tutorial cplusplus.com C++ Language Tutorial Written by: Juan Soulié Last revision: June, 2007 Available online at: http://www.cplusplus.com/doc/tutorial/ The online version is constantly revised and may contain

More information

C++ Programming Language

C++ Programming Language C++ Programming Language Lecturer: Yuri Nefedov 7th and 8th semesters Lectures: 34 hours (7th semester); 32 hours (8th semester). Seminars: 34 hours (7th semester); 32 hours (8th semester). Course abstract

More information

Coding conventions and C++-style

Coding conventions and C++-style Chapter 1 Coding conventions and C++-style This document provides an overview of the general coding conventions that are used throughout oomph-lib. Knowledge of these conventions will greatly facilitate

More information

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

For the next three questions, consider the class declaration: Member function implementations put inline to save space. Instructions: This homework assignment focuses on basic facts regarding classes in C++. Submit your answers via the Curator System as OQ4. For the next three questions, consider the class declaration:

More information

AP Computer Science Java Subset

AP Computer Science Java Subset APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall

More information

CS11 Advanced C++ Spring 2008-2009 Lecture 9 (!!!)

CS11 Advanced C++ Spring 2008-2009 Lecture 9 (!!!) CS11 Advanced C++ Spring 2008-2009 Lecture 9 (!!!) The static Keyword C++ provides the static keyword Also in C, with slightly different usage Used in two main contexts: Declaring static members of a class

More information

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

C++ Outline. cout << Enter two integers: ; int x, y; cin >> x >> y; cout << The sum is:  << x + y << \n ; C++ Outline Notes taken from: - Drake, Caleb. EECS 370 Course Notes, University of Illinois Chicago, Spring 97. Chapters 9, 10, 11, 13.1 & 13.2 - Horstman, Cay S. Mastering Object-Oriented Design in C++.

More information

Inheritance in Programming Languages

Inheritance in Programming Languages Inheritance in Programming Languages Krishnaprasad Thirunarayan Metadata and Languages Laboratory Department of Computer Science and Engineering Wright State University Dayton, OH-45435 INTRODUCTION Inheritance

More information

Practical Programming Methodology. Michael Buro. Class Inheritance (CMPUT-201)

Practical Programming Methodology. Michael Buro. Class Inheritance (CMPUT-201) Practical Programming Methodology (CMPUT-201) Lecture 16 Michael Buro C++ Class Inheritance Assignments ctor, dtor, cctor, assignment op. and Inheritance Virtual Functions Class Inheritance Object Oriented

More information

OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES CONSTRUCTORS AND DESTRUCTORS

OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES CONSTRUCTORS AND DESTRUCTORS CONSTRUCTORS AND DESTRUCTORS Constructors: A constructor is a member function whose name is same as class name and is used to initialize data members and allocate memory dynamically. A constructor is automatically

More information

Classes and Pointers: Some Peculiarities (cont d.)

Classes and Pointers: Some Peculiarities (cont d.) Classes and Pointers: Some Peculiarities (cont d.) Assignment operator Built-in assignment operators for classes with pointer member variables may lead to shallow copying of data FIGURE 3-22 Objects objectone

More information

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.

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. Stewart Weiss Inheritance is a feature that is present in many object-oriented languages such as C++, Eiffel, Java, Ruby, and Smalltalk, but each language implements it in its own way. This chapter explains

More information

Astro Space Center. Profsoyuznaya st., 84/32 Moscow, 117810 Russia, USSR. FAX: 095-310-7023 PHONE: 095-333-21-89 E-MAIL: ikimaileesoci..

Astro Space Center. Profsoyuznaya st., 84/32 Moscow, 117810 Russia, USSR. FAX: 095-310-7023 PHONE: 095-333-21-89 E-MAIL: ikimaileesoci.. LB ESMMONOI MO é IBM PC VLBA recording terminal control software working under MS-DOS. INTRODUCTION. Alexander Novikov and Vitaly Promislov February 1992 Astro Space Center Profsoyuznaya st., 84/32 Moscow,

More information

C++ Essentials. Sharam Hekmat PragSoft Corporation www.pragsoft.com

C++ Essentials. Sharam Hekmat PragSoft Corporation www.pragsoft.com C++ Essentials Sharam Hekmat PragSoft Corporation www.pragsoft.com Contents Contents Preface 1. Preliminaries 1 A Simple C++ Program 2 Compiling a Simple C++ Program 3 How C++ Compilation Works 4 Variables

More information

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void 1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of

More information

Visual Studio 2008 Express Editions

Visual Studio 2008 Express Editions Visual Studio 2008 Express Editions Visual Studio 2008 Installation Instructions Burning a Visual Studio 2008 Express Editions DVD Download (http://www.microsoft.com/express/download/) the Visual Studio

More information

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

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection

More information

MSP430 C/C++ CODE GENERATION TOOLS Compiler Version 3.2.X Parser Error/Warning/Remark List

MSP430 C/C++ CODE GENERATION TOOLS Compiler Version 3.2.X Parser Error/Warning/Remark List MSP430 C/C++ CODE GENERATION TOOLS Compiler Version 3.2.X Parser Error/Warning/Remark List This is a list of the error/warning messages generated by the Texas Instruments C/C++ parser (which we license

More information

Description of Class Mutation Mutation Operators for Java

Description of Class Mutation Mutation Operators for Java Description of Class Mutation Mutation Operators for Java Yu-Seung Ma Electronics and Telecommunications Research Institute, Korea ysma@etri.re.kr Jeff Offutt Software Engineering George Mason University

More information

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

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C 1 An essential part of any embedded system design Programming 2 Programming in Assembly or HLL Processor and memory-sensitive

More information

Ada for the C++ or Java Developer

Ada for the C++ or Java Developer Quentin Ochem Ada for the C++ or Java Developer Release 1.0 Courtesy of July 23, 2013 This work is licensed under a Creative Commons Attribution- NonCommercial-ShareAlike 3.0 Unported License. CONTENTS

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

5 CLASSES CHAPTER. 5.1 Object-Oriented and Procedural Programming. 5.2 Classes and Objects 5.3 Sample Application: A Clock Class

5 CLASSES CHAPTER. 5.1 Object-Oriented and Procedural Programming. 5.2 Classes and Objects 5.3 Sample Application: A Clock Class CHAPTER 5 CLASSES class head class struct identifier base spec union class name 5.1 Object-Oriented and Procedural Programming 5.2 Classes and Objects 5.3 Sample Application: A Clock Class 5.4 Sample Application:

More information