Example 7. na20.nada.kth.se 883)./a.out y = y = y = y = #include <iostream.h> #include <math.

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

13 Classes & Objects with Constructors/Destructors

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

Appendix K Introduction to Microsoft Visual C++ 6.0

C++ INTERVIEW QUESTIONS

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

Member Functions of the istream Class

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

Comp151. Definitions & Declarations

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

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

3 Representation in C++.

C++FA 5.1 PRACTICE MID-TERM EXAM

Basics of I/O Streams and File I/O

EP241 Computer Programming

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Test #4 November 20, True or False (2 points each)

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

arrays C Programming Language - Arrays

Basics of C++ and object orientation in OpenFOAM

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

Chapter 5 Functions. Introducing Functions

Chapter One Introduction to Programming

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

Ch 7-1. Object-Oriented Programming and Classes

Course notes Standard C++ programming

The C Programming Language course syllabus associate level

Chapter 5 Names, Bindings, Type Checking, and Scopes

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

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

Stack Allocation. Run-Time Data Structures. Static Structures

1 Abstract Data Types Information Hiding

Schedule. Structures and Classes in C++ Outline. Goals for This Topic. Another Example of a Structure. What is a Structure? Classes May 12-17, 2005

Object Oriented Software Design II

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

Data Structures using OOP C++ Lecture 1

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

Moving from C++ to VBA

Passing 1D arrays to functions.

Sequential Program Execution

Glossary of Object Oriented Terms

QUEUES. Primitive Queue operations. enqueue (q, x): inserts item x at the rear of the queue q

Object Oriented Software Design II

Java CPD (I) Frans Coenen Department of Computer Science

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

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

Part I. The Picture class

Syllabus OBJECT ORIENTED PROGRAMMING C++

Compiler Construction

Constructor, Destructor, Accessibility and Virtual Functions

Appendix M: Introduction to Microsoft Visual C Express Edition

Example of a Java program

C++ Language Tutorial

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

Note: Syntactically, a ; is needed at the end of a struct definition.

Embedded SQL. Unit 5.1. Dr Gordon Russell, Napier University

Pitfalls in Embedded Software

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

CSI33 Data Structures

Let s put together a Manual Processor

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

Lab 2 - CMPS 1043, Computer Science I Introduction to File Input/Output (I/O) Projects and Solutions (C++)

J a v a Quiz (Unit 3, Test 0 Practice)

Symbol Tables. Introduction

Arrays in Java. Working with Arrays

Answers to Review Questions Chapter 7

Moving from CS 61A Scheme to CS 61B Java

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

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

The little endl that couldn t

Java Interview Questions and Answers

CISC 181 Project 3 Designing Classes for Bank Accounts

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

7.7 Case Study: Calculating Depreciation

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Visual C Tutorial

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

1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright /6/11 12:33 PM!

Chapter 07: Instruction Level Parallelism VLIW, Vector, Array and Multithreaded Processors. Lesson 05: Array Processors

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

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

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

Visual Studio 2008 Express Editions

Parameter passing in LISP

COMPUTER SCIENCE 1999 (Delhi Board)

Programming Language Features (cont.) CMSC 330: Organization of Programming Languages. Parameter Passing in OCaml. Call-by-Value

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

C++ Input/Output: Streams

C++ Overloading, Constructors, Assignment operator

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

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

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Transcription:

In the example above two functions are defined. Both increments the value of i by one, but fcn1 uses call-by-value as parameter passing mechanism and fcn2 uses call-by-reference. call-by-value means that a local copy of the variable is created in fcn1, the local copy is incremented by one. It will not affect the actual parameter in the calling program (nr print). call-by-value is used for input of values to the function. call-by-reference means that the variable i in fcn2 refers to the same variable as the actual parameter in the calling program, (nr print), so that when i is incremented in fcn2 it will also affect the value of the actual parameter. Call-by-reference is used when the parameter should transfer a value from the function (output parameter). Note also that When no return value is used, the function return type can be declared void. The underscore character canbeusedinvariablenames. InC ++ it has the same status as a letter. Example from running the program is na20.nada.kth.se 883)./a.out 0 1 2 2 #include <iostream.h> #include <math.h> Example 7 double scprod( int n, double x[], double y[] ); double x[10], y[10]; for( int i = 0 ; i < 10 ; i++ ) x[i] = i; y[i] = sin(x[i]); 8

cout << "Scalar product is " << scprod( 10, x, y ) << endl; double scprod( int n, double x[], double y[] ) double sum = 0; for( int i=0 ; i < n ; i++ ) sum += x[i]*y[i]; return sum; Above is an example of using arrays in C++. The function scprod computes the scalar product of the two vector parameters. The size of the array (10) in this case, must be given as a fixed number in the main program. The compiler reserves memory for the vector, so the size must be known when the program is compiled. A vector is declared with 10 elements, the elements are x[0], x[1],...,x[9]. Indexes always start from 0 in Cand C++. In a function, it is possible to leave out the size of a vector parameter. Arrays are passed as call-by-reference, so no memory needs to be allocated for the function parameters during the compilation. #include <iostream.h> Example 8 double scprod( int n, double x[], double y[] ); double *x, *y; cout << "Give vector size "; int n; cin >> n; x = new double[n]; y = new double[n]; for( int i = 0 ; i < n ; i++ ) x[i] = i; y[i] = sin(x[i]); cout << "Scalar product is " << scprod( n, x, y ) << endl; delete[] x; delete[] y; 9

This example shows the same thing as Example 7, but using dynamically allocated memory instead. Dynamic memory should be used when the size of the array can not be known when the program is compiled. Note that: The new statement allocates memory, in this case a double vector of n elements. Do not use new as a name for variables. The function scprod is used unchanged from Example 7. The memory is removed by delete[]. It is important to remember to delete memory which is no longer needed. If this is forgotten, for example inside a function which is called often, a so called memory leak has appeared. After many calls to the function, the memory will be used up and the program terminates with an error. All memory is deleted automatically when main finishes, so the delete statements in the code above are not really necessary. There are programming languages, for example Java, which can delete unused memory automatically, but in C++ we have to do it ourselves. x and y are declared as pointers (*x, *y). A vector in C++ is understood as a pointer to a sequence of variables. Element x[i] can equally well be refered to as *(x+i), which means what x plus i locations further points to. #include <iostream> using namespace std; class point private: int x; int y; public: point( int xi, int yi ); void move( int dx, int dy ); void wri(); ; point::point( int xi, int yi ) x = xi; y = yi; Example 9 10

void point::move( int dx, int dy ) x += dx; y += dy; void point::wri() cout << "(x,y) = " << x << "," << y << endl; point a(5,2); a.move(-2,4); point b(1,-1); b.wri(); a=b; This example shows the use of a class. A class is a datatype consisting of several variables and functions. The data and functions can be declared as private or public. The private data and functions can only be used by functions inside the class. The public data can be accessed from the outside. private is the default, if nothing else is written. Functions are declared inside the class. They can be defined there as well. In the example above the functions are instead defined outside of the class. In this case it is necessary to add classname:: to the function name, in order to distinguish between functions of the same name but which belong to different classes. The class is only a description of the data type, and does not allocate place in memory. It is the objects a and b in the main program that are the variables in memory, of the type described by the class declaration. The special function which has the same name as the class, and is without return type, is called constructor and is called automatically when an object is created. The purpose of the constructor is to ensure that all variables are initialized in a correct way. 11

The main program can only access the public part of the objects. This is done by the dot-notation (a.wri()). One of the ideas of object orientation is to hide the internal representation of the class from the main program. It is possible for example, to replace the variables x and y by a vector x[2] inside the class. The functions in the class have then to be rewritten, but the main program does not need to be changed. Thus all changes are kept as local as possible. This is of importance when the program is very big. Example from running the program: na20.nada.kth.se 962)./a.out (x,y) = 5,2 (x,y) = 3,6 (x,y) = 1,-1 (x,y) = 1,-1 12