introduction to c++rcs.bu.edu/examples/cpp/tutorial/introduction to c++.pdf · 2020. 9. 21. · a...

167
Introduction to C++ tutorial version 0.7 Research Computing Services

Upload: others

Post on 29-Jul-2021

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Introduction to C++tutorial version 0.7

Research Computing Services

Page 2: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Existing SCC Account

1. Open a web browser

2. Navigate to http://scc-ondemand.bu.edu

3. Log in with your BU Kerberos Credentials

Temporary Tutorial Account

1. Open a web browser

2. Navigate to https://scc-ondemand-tutorial.bu.edu

3. Log in with Tutorial Account

4. Username: tuta# where # is 10-99

5. The password will be given in the Zoom chat.

Page 3: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Click on Interactive Apps/Desktop

Page 4: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

3

eclipse/2019-06

click

Page 5: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

When your desktop is ready click Connect to Desktop

Page 6: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Enter this command to create a directory in your home folder and to copy

in tutorial files:

Also get the tutorial slides here:

/net/scc2/scratch/intro_to_cpp.sh

http://rcs.bu.edu/examples/cpp/tutorial/

Page 7: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Run the Eclipse software

Enter this command to start up the Eclipse development

environment.

When this window appears just click the Launch button:

eclipse &

Page 8: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Run the Eclipse software

When this window appears just leave it be for now.

Page 9: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Tutorial Outline

Intro to C++

Object oriented concepts

Write a first program

Using C++ objects

Standard Template Library

Basic debugging

Defining C++ classes

Look at the details of how they

work

Class inheritance

Virtual methods

Available C++ tools on the

SCC

Page 10: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Tutorial Outline

Very brief history of C++

Definition object-oriented programming

When C++ is a good choice

The Eclipse IDE

Object-oriented concepts

First program!

Some C++ syntax

Function calls

Page 11: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Very brief history of C++

For details more check out A History of C++: 1979−1991

C

C++

Page 12: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Object-oriented programming

OOP defines classes to represent

these things.

Classes can contain data and methods

(internal functions).

Classes control access to internal data

and methods. A public interface is

used by external code when using the

class.

This is a highly effective way of

modeling real world problems inside of

a computer program.

public interface

private data and methods

“Class Car”

Page 13: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Characteristics of C++“Actually I made up the term ‘object-oriented’, and I can tell you I did

not have C++ in mind.”

– Alan Kay (helped invent OO programming, the Smalltalk language, and the GUI)

C++ is…

Compiled.

A separate program, the compiler, is used to turn C++ source code into a form directly

executed by the CPU.

Strongly typed and unsafe

Conversions between variable types must be made by the programmer (strong typing) but can

be circumvented when needed (unsafe)

C compatible

call C libraries directly and C code is nearly 100% valid C++ code.

Capable of very high performance

The programmer has a very large amount of control over the program execution, compilers

are high quality.

Object oriented

With support for many programming styles (procedural, functional, etc.)

No automatic memory management (mostly)

The programmer is in control of memory usage

Page 14: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

When to choose C++

Despite its many competitors C++ has remained popular for ~30 years and will

continue to be so in the foreseeable future.

Why?

Complex problems and programs can be effectively implemented

OOP works in the real world.

No other language quite matches C++’s combination of performance, libraries,

expressiveness, and ability to handle complex programs.

Page 15: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

When to choose C++

Choose C++ when:

Program performance matters

Dealing with large amounts of data, multiple CPUs, complex algorithms, etc.

Programmer productivity is less important

You’ll get more code written in less time in a languages like Python, R, Matlab, etc.

The programming language itself can help organize your code

In C++ your objects can closely model elements of your problem

Complex data structures can be implemented

Access to a vast number of libraries

Your group uses it already!

“If you’re not at all interested in performance, shouldn’t you

be in the Python room down the hall?”

― Scott Meyers (author of Effective Modern C++)

Page 16: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Eclipse https://www.eclipse.org

In this tutorial we will use the Eclipse integrated development environment

(IDE) for writing and compiling C++

About Eclipse Started in 2001 by IBM.

The Eclipse Foundation (2004) is an independent, non-profit corporation that maintains and

promotes the Eclipse platform.

Cross-platform: supported on Mac OSX, Linux, and Windows

Supports numerous languages: C++, C, Fortran, Java, Python, and more.

A complex tool that can be used by large software teams.

Page 17: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

IDE Advantages

Handles build process for you

Syntax highlighting and live error detection

Code completion (fills in as you type)

Creation of files via templates

Built-in debugging

Code refactoring (ex. Change a variable

name everywhere in your code)

Much higher productivity compared with

plain text editors! …once you learn how to use it.

IDEs available on the SCC

Eclipse (used here)

geany – a minimalist IDE, simple to use

Netbeans – used in past C++ tutorials.

Simpler than Eclipse but still capable.

Spyder – Python only, part of Anaconda

Emacs – The one and only.

Some Others

Xcode for Mac OSX

Visual Studio for Windows

Visual Studio Core plus plugins

Code::Blocks (cross platform)

Page 18: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

A first program

Click Create a new C++ project

in the Eclipse window.

Page 19: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

A first program

For a project name use hello_world

Choose a Hello World C++ Project

and the Linux GCC toolchain.

This version of Eclipse is their “IDE

for Scientific Computing” package.

Then click the Next button.

Page 20: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

A first program

Add your name

Everything else can stay the same.

Click Next.

Page 21: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

A first program

Last screen. Don’t change anything

here, just click Finish.

Page 22: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

A first program Now click the Workbench button in the welcome screen to go to the newly

created project.

Page 23: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

hello_world.cpp

has been auto-

generated.

Under the Project

menu select the

Build Project

option.

Then click the

Run button:

Page 24: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Behind the Scenes: The Compilation Process

Page 25: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Hello, World! explained The main routine – the start of every C++ program! It

returns an integer value to the operating system and (in

this case) takes arguments to allow access to command

line arguments.

The return statement returns an integer value to the

operating system after completion. 0 means “no error”. C++

programs must return an integer value.

The two characters // together indicate a comment that is

ignored by the compiler.

Page 26: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Hello, World! explained

loads a header file containing function and class

definitions

Loads a namespace called std.

Namespaces are used to separate sections of code

for programmer convenience. To save typing we’ll

always use this line in this tutorial.

cout is the object that writes to the stdout device, i.e. the console

window.

It is part of the C++ standard library.

Without the “using namespace std;” line this would have been called

as std::cout. It is defined in the iostream header file.

<< is the C++ insertion operator. It is used to pass characters from

the right to the object on the left.

endl is the C++ newline character.

Page 27: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Header Files

C++ (along with C) uses header files as to hold definitions for the compiler to use while

compiling.

A source file (file.cpp) contains the code that is compiled into an object file (file.o).

The header (file.h) is used to tell the compiler what to expect when it assembles the

program in the linking stage from the object files.

Source files and header files can refer to any number of other header files.

When compiling the linker connects all of the object (.o) files together into the

executable.

Page 28: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Make some changes

Let’s put the message into some variables

of type string and print some numbers.

Things to note:

Strings can be concatenated with a + operator.

No messing with null terminators or strcat() as in

C

Some string notes:

Access a string character by brackets or

function:

msg[0] “H” or msg.at(0) “H”

C++ strings are mutable – they can be

changed in place.

Re-run and check out the output.

#include <iostream>

using namespace std;

int main() {

string hello = "Hello";

string world = "world!";

string msg = hello + " " +

world ;

cout << msg << endl;

msg[0] = 'h';

cout << msg << endl;

return 0;

}

Page 29: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

A first C++ class: string

string is not a basic type (more

on those later), it is a class.

string hello creates an

instance of a string called hello.

hello is an object. It is

initialized to contain the string

“Hello”.

A class defines some data and a

set of functions (methods) that

operate on that data.

#include <iostream>

using namespace std;

int main() {

string hello = "Hello";

string world = "world!";

string msg = hello + " " +

world ;

cout << msg << endl;

msg[0] = 'h';

cout << msg << endl;

return 0;

}

Page 30: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

A first C++ class: string

Update the code as you see

here.

After the last character is entered

Eclipse will display a large

number of methods defined for

the msg object.

If you click or type something

else just delete and re-type the

trailing period.

#include <iostream>

using namespace std;

int main() {

string hello = "Hello";

string world = "world!";

string msg = hello + " " + world ;

cout << msg << endl;

msg[0] = 'h';

cout << msg << endl;

msg.

return 0;

}

Page 31: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

A first C++ class: string

Start typing the word size until

it appears in the menu.

Hit the Enter key to accept it.

Now hover your mouse cursor

over the msg.size() code and a

help window will pop up.

Page 32: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

A first C++ class: string

Tweak the code to print the number

of characters in the string, build, and

run it.

size() is a public method, usable by

code that creates the object.

The internal tracking of the size and

the storage itself is private, visible

only inside the string class source

code.

cout prints integers

without any modification!

#include <iostream>

using namespace std;

int main()

{

string hello = "Hello" ;

string world = "world!" ;

string msg = hello + " " + world ;

cout << msg << endl ;

msg[0] = 'h';

cout << msg << endl ;

cout << msg.size() << endl ;

return 0;

}

Page 33: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Break your code.

Remove a semi-colon. Re-compile. What messages do you get from the

compiler and Eclipse?

Fix that and break something else. Capitalize string String

C++ can have elaborate error messages when compiling. Experience is

the only way to learn to interpret them!

Fix your code so it still compiles and then we’ll move on…

Page 34: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

C++ syntax is very similar to C, Java, or C#. Here’s a few things up front and we’ll cover

more as we go along.

Curly braces are used to denote a code block (like the main() function):

Statements end with a semicolon:

Comments are marked for a single line with a // or for multilines with a pair of /* and */ :

Variables can be declared at any time in a code block.

Basic Syntax

void my_function() {

int a ;

a=1 ;

int b;

}

int a ;

a = 1 + 3 ;

// this is a comment.

/* everything in here

is a comment */

{ … some code… }

Page 35: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Functions are sections of code that are called from other code. Functions always have a

return argument type, a function name, and then a list of arguments separated by

commas:

A void type means the function does not return a value.

Variables are declared with a type and a name:

int add(int x, int y) {

int z = x + y ;

return z ;

}

// No arguments? Still need ()

void my_function() {

/* do something...

but a void value means the

return statement can be skipped.*/

}

// Specify the type

int x = 100;

float y;

vector<string> vec ;

// Sometimes types can be

// inferred in C++11

auto z = x;

Page 36: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

A sampling of arithmetic operators:

Arithmetic: + - * / % ++ --

Logical: && (AND) ||(OR) !(NOT)

Comparison: == > < >= <= !=

Sometimes these can have special meanings beyond arithmetic, for

example the “+” is used to concatenate strings.

What happens when a syntax error is made? The compiler will complain and refuse to compile the file.

The error message usually directs you to the error but sometimes the error occurs before the

compiler discovers syntax errors so you hunt a little bit.

Page 37: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Built-in (aka primitive or intrinsic) Types

“primitive” or “intrinsic” means these types are not objects. They have no methods or internal hidden data.

Here are the most commonly used types.

Note: The exact bit ranges here are platform and compiler dependent!

Typical usage with PCs, Macs, Linux, etc. use these values

Variations from this table are found in specialized applications like embedded system processors.

Name Name Value

char unsigned char 8-bit integer

short unsigned short 16-bit integer

int unsigned int 32-bit integer

long unsigned long 64-bit integer

bool true or false

Name Value

float 32-bit floating point

double 64-bit floating point

long long 128-bit integer

long double 128-bit floating point

http://www.cplusplus.com/doc/tutorial/variables/

Page 38: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Read-Only Types

The const keyword can be combined with any type declaration to make

read-only variables.

Assignment can happen during a function call.

The compiler will stop with an error if a const variable has a new value

assigned to it in your code.

const float pi = 3.14 ;

const string w = "Const String" ;

Page 39: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Need to be sure of integer sizes?

In the same spirit as using integer(kind=8) type notation in Fortran, there are type definitions that

exactly specify exactly the bits used. These were added in C++11.

These can be useful if you are planning to port code across CPU architectures (ex. Intel 64-bit

CPUs to a 32-bit ARM on an embedded board) or when doing particular types of integer math.

For a full list and description see: http://www.cplusplus.com/reference/cstdint/

Name Name Value

int8_t uint8_t 8-bit integer

int16_t uint16_t 16-bit integer

int32_t uint32_t 32-bit integer

int64_t uint64_t 64-bit integer

#include <cstdint>

Page 40: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Reference and Pointer Variables

Variable and object values are stored in particular locations in the computer’s memory.

Reference and pointer variables store the memory location of other variables.

Pointers are found in C. References are a C++ variation that makes pointers easier and safer to

use.

More on this topic later in the tutorial.

string hello = "Hello";

string *hello_ptr = &hello;

string &hello_ref = hello;

The object hello

occupies some

computer memory.

A pointer to the hello object string. hello_ptr

is assigned the memory address of object

hello which is accessed with the “&” syntax.

hello_ref is a reference to a string. The hello_ref

variable is assigned the memory address of object hello

automatically.

Page 41: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

C++ is strongly typed. It will auto-convert a variable of one type to another where it can.

Conversions that don’t change value work as expected:

increasing precision (float double) or integer floating point of at least the same precision.

Loss of precision usually works fine:

64-bit double precision 32-bit single precision.

But…be careful with this, if the larger precision value is too large the result might not be what you expect!

Type Casting

short x = 1 ;

int y = x ; // OK

string z = y ; // NO

Page 42: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

C++ allows for C-style type casting with the syntax: (new type) expression

But when using C++ it’s best to stick with deliberate type casting using the 4 different

ways that are offered…

Type Casting

double x = 1.0 ;

int y = (int) x ;

float z = (float) (x / y) ;

Page 43: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Type Casting

static_cast<new type>( expression )

This is exactly equivalent to the C style cast.

This identifies a cast at compile time.

This makes it clear to another programmer that you really intended a cast that

reduces precision (ex. double float) even if it would happen automatically.

~99% of all your casts in C++ will be of this type.

dynamic_cast<new type>( expression)

Special version where type casting is performed at runtime, only works on reference

or pointer type variables.

Usually created automatically by the compiler where needed, rarely done by the

programmer.

double d = 1234.56 ;

float f = static_cast<float>(d) ;

// same as

float g = (float) d ;

// same as

float h = d ;

Page 44: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Type Casting – rarely used versions

const_cast<new type>( expression )

Variables labeled as const can’t have their value changed.

const_cast lets the programmer remove or add const to reference or pointer type

variables.

If you need to do this, you probably want to re-think your code!

reinterpret_cast<new type>( expression )

Takes the bits in the expression and re-uses them unconverted as a new type. Also

only works on reference or pointer type variables.

Sometimes useful when reading or writing binary files or when dealing with hardware

devices like serial or USB ports.

“unsafe”: the

compiler will not

protect you here!

The programmer

must make sure

everything is

correct!

Danger!

Page 45: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

float RectangleArea1(float L, float W) {

return L*W ;

}

float RectangleArea2(const float L, const float W) {

// L=2.0 ;

return L*W ;

}

float RectangleArea3(const float& L, const float& W) {

return L*W ;

}

void RectangleArea4(const float& L, const float& W,

float& area) {

area= L*W ;

}

Functions

Open the project “FunctionExample” in

the Part 1 Eclipse project file. Compile and run it!

Open Functions.cpp

4 function calls are listed.

The 1st and 2nd functions are identical in

their behavior. The values of L and W are sent to the function,

multiplied, and the product is returned.

RectangleArea2 uses const arguments The compiler will not let you modify their values in the

function.

Try it! Uncomment the line and see what happens

when you recompile.

The 3rd and 4th versions pass the

arguments by reference with an added &

The function arguments L and W

are sent as type float.

Product is computed and returned

The return type is float.

Page 46: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Organization of FunctionExample

Functions.cpp Code that implements 4 functions.

Functions.h Header file that declares the 4 functions.

FunctionExample.cpp Contains the “main” routine.

Includes the Functions.h file so the 4 functions can be called.

FunctionExample.cpp and Functions.cpp are compiled separately. The header file insures the code being generated and being called is correct.

The FunctionExample.o and Functions.o object files are linked to make the executable.

Page 47: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Using the Eclipse Debugger

To show how these functions work we will use the Eclipse interactive debugger to step through the program

line-by-line to follow the function calls.

Click the Debug button:

Page 48: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Add Breakpoints

Breakpoints tell the debugger to halt at a

particular line so that the state of the

program can be inspected.

Right-click over the line numbers, go to

Breakpoint Types and choose C/C++

Breakpoints

Double click next to the line numbers in

the functions to add breakpoints.

Click the green arrow in the toolbar to

resume the program.

Page 49: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

The debugger will pause the

program at the first

breakpoint.

In the right hand window

you’ll see the argument

values. Click one for details.

Let’s step through this:

Page 50: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Tutorial Outline

Compiler Options

References and Pointers

Function Overloads

Generic Functions

Intro to the Standard Template Library

Page 51: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Compiler Options

We’ve been working with Eclipse using a Debug build. This is determined by the options

set for the compiler.

The g++ compiler has a vast array of options:

https://gcc.gnu.org/onlinedocs/gcc-4.8.5/gcc/index.html#toc_Invoking-GCC

The -g flag tells the compiler to add extra information to the executable to allow the

debugger to read and manipulate the program.

Turning on optimizations makes the compiler do more work to produce code that will

execute faster. This is used in the Eclipse Release build.

What happens in optimization? https://en.wikipedia.org/wiki/Optimizing_compiler

Page 52: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Compiler Options (for g++ 4.8.5)

Common flags: -g Support for debugging. Sometimes not completely effective with (any) optimization turned

on.

-Og Optimize but don’t do anything that will cause issues while running the debugger.

-O, -O2, -O3 Produce optimized code. The higher numbers let the compiler try more

strategies to generate code. They are less likely to have an impact.

Can be combined with -g but makes debugging more difficult.

-ffast-math -funsafe-math-optimizations May produce code that does not conform to IEEE

standards for floating point computations. Try it with your program and see if it has any impact

on accuracy and/or speed.

-march=corei7 On the SCC, allow for some special CPU instructions to be generated for

calculations in loops that may result in faster code.

Page 53: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Using Compiler Options

An IDE like Eclipse will apply these for you when building.

On the command line (for a single source file program):

g++ -o my_program -g my_source.cpp

g++ -o my_program -O3 my_source.cpp

Debug

Release

g++ -o my_program –g -Og my_source.cppDebug with

optimizations

Page 54: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Pass by Value

C++ defaults to pass by value behavior when calling a function.

The function arguments are copied when used in the function.

Changing the value of L or W in the RectangleArea1 function does not effect their original values in

the main() function

When passing objects as function arguments it is important to be aware that potentially large data

structures are automatically copied!

main()

float L

float W

RectangleArea1(float L, float W)

float L

float W

copy

copy

Page 55: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Pass by Reference

Pass by reference behavior is triggered when the & character is used to modify the type of the

argument.

This is the type of behavior you see in Fortran, Matlab, Python, and others.

Pass by reference function arguments are NOT copied. Instead the compiler sends a pointer to the

function that references the memory location of the original variable. The syntax of using the

argument in the function does not change.

Pass by reference arguments almost always act just like a pass by value argument when writing

code EXCEPT that changing their value changes the value of the original variable!!

The const modifier can be used to prevent changes to the original variable in main().

main()

float L

float W

RectangleArea3(const float& L, const float& W)

float L

float W

reference

reference

Page 56: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

In RectangleArea4 the pass by reference behavior is used as a way to

return the result without the function returning a value.

The value of the area argument is modified in the main() routine by the

function.

This can be a useful way for a function to return multiple values in the

calling routine.

void RectangleArea4(const float& L, const float& W, float& area) {

area= L*W ;

}

void does not return a value.

Page 57: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

In C++ arguments to functions can be objects… Example: Consider a string variable containing 1 million characters (approx. 1 MB of RAM).

Pass by value requires a copy – 1 MB

pass by reference requires 8 bytes!

“C makes it easy to shoot yourself in the foot; C++ makes it harder, but

when you do it blows your whole leg off.” – Bjarne Stroustrop

Page 58: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Rules of thumb for function/method arguments

Basic types (int, float, etc) just pass by value unless you need to modify

values in a calling function. int - 4 bytes

int& - 8 bytes (64-bit memory address)

Pass all objects by reference. use the const modifier whenever appropriate to protect yourself from accidentally modifying

variables.

Page 59: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Tutorial Outline

Compiler Options

References and Pointers

Function Overloads

Generic Functions

Intro to the Standard Template Library

Page 60: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Function overloading

The same function can be implemented

multiple times with different arguments.

This allows for special cases to be

handled, or specialized behavior for

different types.

cout and the << operator are an example

of function overloading << is just a function.

float sum(float a, float b) {

return a+b ;

}

int sum(int a, int b) {

return a+b ;

}

Page 61: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Function overloading

Overloaded functions are differentiated

by their arguments and not the return

type. The number of arguments and their types can be

varied.

The compiler will decide which overload

to use depending on the types of the

arguments.

If it can’t decide a compile-time error will

occur.

float sum(float a, float b) {

return a+b ;

}

int sum(int a, int b) {

return a+b ;

}

Page 62: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

C++ Templates (aka generics)

Generic code is code that works on multiple different data types but is

only coded once.

In C++ this is called a template.

A C++ template is implemented entirely in a header file to define

generic classes and functions.

The actual code is generated by the compiler wherever the template

is used in your code.

There is NO PENALTY when your code is running!

Page 63: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

C++ Templates (aka generics)

Template code should be placed in header (.h) files.

A source code file (.cpp) is not needed for template code.

Expect longer compile times – the compiler has to do a lot more work.

Executing code created by templates is often much faster when

compiler optimizations are turned on.

Page 64: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Sample template function

The template is started with the keyword

template and is told it’ll handle a type which is

referred to as T in the code.

Templates can be created with multiple different

types, not limited to just one.

You don’t have to use T, any non-reserved word will

do.

Specialize the template to the type you want to

use.

// In a header file

template <typename T>

T sum_template (T a, T b) {

return a+b ;

}

// Then call the function in a

// source file:

float x=1.0 ;

float y=2.0 ;

auto z=sum_template<float>(x,y) ;

Page 65: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

An Example

Open the project Overloads_and_templates

This is an example of simple function overloads and a template function.

Let’s walk through it with the debugger.

Page 66: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

When to use function overloading and templates?

When it makes your code easier to use, maintain, write, or debug! Overloads are easier to use effectively.

Templating everything in your code does not make it better, just harder to

develop. Longer compiles, harder to debug, etc.

More experienced C++ programmers should use these features where

appropriate.

Page 67: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Stepping back a bit

Summary so far: Basics of C++ syntax

Declaring variables

Defining functions

Using the IDE

As an object-oriented language C++ supports a core set of OOP

concepts.

Knowing these concepts help with understanding some of the underlying

design of the language and how it operates in your programs.

Page 68: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

The formal concepts in OOP

The core concepts in addition to

classes and objects are: Encapsulation

Inheritance

Polymorphism

Abstraction

Polymorphism

Encapsulation

Inheritance

Abstraction

OOP

Page 69: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Core Concepts

Encapsulation

Bundles related data and functions

into a class

Inheritance

Builds a relationship between classes

to share class members and methods

Abstraction

The hiding of members, methods,

and implementation details inside of a

class.

Polymorphism

The application of the same code to

multiple data types

Page 70: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Core Concepts in this tutorial

Encapsulation

Demonstrated by writing some

classes

Inheritance

Write classes that inherit (re-use) the

code from other classes.

Abstraction

Design and setup of classes,

discussion of the Standard Template

Library (STL).

Polymorphism

Function overloading, template code,

and the STL

Page 71: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Tutorial Outline

Compiler Options

References and Pointers

Function Overloads

Generic Functions

Intro to the Standard Template Library

Page 72: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

The Standard Template Library

The STL is a large collection of containers and algorithms that are part of

C++. It provides many of the basic algorithms and data structures used in computer science.

As the name implies, it consists of generic code that you specialize as

needed.

The STL is: Well-vetted and tested.

Well-documented with lots of resources available for help.

Page 73: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Containers

There are 16 types of containers in the STL:

Container Description

array 1D list of elements.

vector 1D list of elements

deque Double ended queue

forward_list Linked list

list Double-linked list

stack Last-in, first-out list.

queue First-in, first-out list.

priority_queue 1st element is always the

largest in the container

Container Description

set Unique collection in a specific

order

multiset Elements stored in a specific

order, can have duplicates.

map Key-value storage in a specific

order

multimap Like a map but values can

have the same key.

unordered_set Same as set, sans ordering

unordered_multiset Same as multisetset, sans

ordering

unordered_map Same as map, sans ordering

unordered_multimap Same as multimap, sans

ordering

Page 74: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Algorithms

There are 85+ of these.

Example: find, count, replace, sort, is_sorted, max, min, binary_search, reverse

Algorithms manipulate the data stored in containers but is not tied to STL containers

These can be applied to your own collections or containers of data

Example:

The implementation is hidden and the necessary code for reverse() is generated from

templates at compile time.

vector<int> v(3); // Declare a vector of 3 elements.

v[0] = 7;

v[1] = 3;

v[2] = v[0] + v[1]; // v[0] == 7, v[1] == 3, v[2] == 10

reverse(v.begin(), v.end()) ; // v[0] == 10, v[1] == 3, v[2] == 7

Page 75: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

vector<T> A very common and useful class in C++ is the vector class. Access it with:

Vector has many methods:

Various constructors

Ways to iterate or loop through its contents

Copy or assign to another vector

Query vector for the number of elements it contains or its backing storage size.

Example usage: vector<float> my_vec ;

Or: vector<float> my_vec(50) ;

#include <vector>

Page 76: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Hidden from the programmer is the backing store

Object oriented design in action!

This is how the vector stores its data internally.

vector<T>

Contains N elements. Given by size() method.

Allocated for a total of M

elements

Given by capacity() method.

Add some more to the vector

New memory is allocated.

Old data is copied in.

New M > old M.

Old allocation is destroyed.

Allocated for a total of M’

elements

Page 77: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Construction and Destruction

A special function called the

constructor is called when an

object is created.

This is used to initialize an object:

Load values into member variables

Open files

Connect to hardware, databases,

networks, etc.

The destructor is called when an

object goes out of scope.

Example:

Object c1 is created when the

program reaches the first line of

the function, and destroyed when

the program leaves the function.

void function() {

ClassOne c1 ;

}

Page 78: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Scope Scope is the region where a variable is valid.

Constructors are called when an object is created.

Destructors are called automatically when a variable is out of scope.

int main() { // Start of a code block

// in main function scope

float x ; // No constructors for built-in types

ClassOne c1 ; // c1 constructor ClassOne() is called.

if (1){ // Start of an inner code block

// scope of c2 is this inner code block

ClassOne c2 ; //c2 constructor ClassOne() is called.

} // c2 destructor is called.

ClassOne c3 ; // c3 constructor ClassOne() is called.

} // leaving program, call destructors for c3 and c1 in that order

// variable x: no destructor for built-in type

Page 79: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Destructors

vector<t> can hold most types of objects: Primitive (aka basic) types: int, float, char, etc.

Objects: string, your own classes, file objects, etc.

Pointers: int*, string*, etc.

But NOT references!

When a vector is destroyed: If it holds primitive types or pointers it just deallocates its backing store.

If it holds objects it will call each object’s destructor before freeing its backing store.

Page 80: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

vector<t> with objects

Select an object in a vector.

The members and methods can be

accessed directly.

Elements can be accessed with

brackets and an integer starting

from 0.

// a vector with memory preallocated to

// hold 1000 objects.

vector<MyClass> my_vec(1000);

// Now make a vector with 1000 MyClass objects

// that are initialized using the MyClass constructor

vector<MyClass> my_vec2(1000,MyClass(arg1,arg2));

// Access an object's method.

my_vec2[100].some_method() ;

// Or a member

my_vec2[10].member_integer = 100 ;

// Clear out the entire vector

my_vec2.clear()

// but that might not re-set the backing store…

// Let’s check the docs:

// http://www.cplusplus.com/reference/vector/vector/clear/

Page 81: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Loop with a “for” loop, referencing the value of vec using brackets.

1st time through: index = 0

Print value at vec[0]

index gets incremented by 1

2nd time through: Index = 1

Etc

After last time through Index now equal to vec.size()

Loop exits

Careful! Using an out of range index will likely cause a memory error that crashes your

program.

for (int index = 0 ; index < vec.size() ; ++index)

{

// ++index means "add 1 to the value of index"

cout << vec[index] << " " ;

}

Loopin

g

Page 82: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Iterators

Iterators are generalized ways of keeping track of positions in a container.

3 types: forward iterators, bidirectional, random access

Forward iterators can only be incremented (as seen here)

Bidirectional can be added or subtracted to move both directions

Random access can be used to access the container at any location

v[0] v[1] v[2]v.begin()

v.begin()+1

v.begin()+2

v.end()

Page 83: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

for (vector<int>::iterator itr = vec.begin(); itr != vec.end() ; ++itr)

{

cout << *itr << " " ;

// iterators are pointers!

}

Loop with a “for” loop, referencing the value of vec using an iterator type.

vector<int>::iterator is a type that iterates through a vector of int’s.

1st time through:

itr points at 1st element in vec

Print value pointed at by itr: *itr

itr is incremented to the next element in the vector

Iterators are very useful C++ concepts. They work on any STL container!

No need to worry about the # of elements!

Exact iterator behavior depends on the type of container but they are guaranteed to always

reach every value.

Loopin

g

Page 84: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Let the auto type asks the C++ compiler to figure out the iterator type automatically.

An extra modification: Assigning the vec_end variable avoids calling vec.end() on every loop.

for (auto itr = vec.begin() ; itr != vec.end() ; ++itr)

{

cout << *itr << " " ;

}

Loopin

g

for (auto itr = vec.begin(), auto vec_end = vec.end() ; itr != vec_end ; ++itr)

{

cout << *itr << " " ;

}

Page 85: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Another iterator-based loop: iterator behavior and accessing an element are handled

automatically by the compiler

Uses a reference so the element is not copied.

The const auto & prevents changes to the element in the vector.

If you don’t use const then the loop can update the vector elements via the reference.

Less typing == less chance for program bugs.

for(const auto &element : vec)

{

cout << element << " " ;

}

Loopin

g

Page 86: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Iterator notes There is small performance penalty for using iterators…but are they safer to use.

They allow substitution of one container for another (list<> for vector<>, etc.)

With templates you can write a function that accepts any STL container type.

template<typename T>

void dump_string(T &t)

{

for( auto itr=t.begin() ; itr!=t.end() ; itr++) {

cout << *itr << endl;

}

}

list<float> lst ;

lst.push_back(-5.0) ;

lst.push_back(12.0) ;

vector<double> vec(2) ;

vec[0] = 1.0 ;

vec[1] = 2.0 ;

dump_string<list<float> >(lst) ;

dump_string<vector<double> >(lst) ;

Page 87: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

STL Demo

Open project STL_Demo

Let’s walk through the functions with the debugger and see

some vectors in action.

Page 88: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

C++ File Reading with the STL

Open project STL_IO

This is a small sample

program that will read in a

column of numbers from a

text file.

Let’s try this out and modify

the code to calculate some

statistics from the numbers.

Page 89: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Tutorial Outline

Defining Classes

Class inheritance

Public, private, and protected access

Virtual functions

Page 90: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

A first C++ class

Open project Basic_Rectangle.

We’ll add our own custom class to this project.

A C++ class consists of 2 files: a header file (.h) and a source file (.cpp)

The header file contains the definitions for the types and names of members, methods, and

how the class relates to other classes (if it does).

The source file contains the code that implements the functionality of the class

Sometimes there is a header file for a class but no source file.

Page 91: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Using Eclipse

An IDE is very useful for setting up code that follows patterns and configuring the build

system to compile them.

This saves time and effort for the programmer.

Right-click on the Basic_Rectangle project and choose NewClass

Page 92: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Give it the name

Rectangle and click

the Finish button.

Open the new files

Rectangle.h and

Rectangle.cpp

Page 93: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Rectangle.h

keyword

Class name

Curly brace

Curly brace

and a

semi-colon.

Access

control

Page 94: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Default declared methods

Rectangle(); A constructor. Called when an object of this class is

created.

~Rectangle(); A destructor. Called when an object of this class is

removed from memory, i.e. destroyed.

Ignore the virtual keyword for now.

Page 95: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Rectangle.cpp

Header file included

Class_name:: pattern indicates

the method declared in the header

is being implemented in code

here.

Methods are otherwise regular

functions with arguments () and

matched curly braces {}.

Page 96: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Let’s add some functionality

A Rectangle class should store a

length and a width.

To make it useful, let’s have it

supply an Area() method to

compute its own area.

Edit the header file to look like the

code to the right.

Page 97: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Encapsulation

Bundling the data and area calculation for a rectangle into a

single class is an example of the concept of encapsulation.

Page 98: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

The code for the two methods is needed

Right-click in the Rectangle.h

window and choose

SourceImplement Methods

Page 99: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Click Select All then click OK.

Page 100: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Fill in the methods

Member variables can be accessed as though they were passed to the method.

Methods can also call each other.

Fill in the Area() method and then write your own ScaledArea(). Don’t forget to compile!

Step 1: add some comments.

Step 2: add some code.

Page 101: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Using the new class

Open Basic_Rectangle.cpp

Add an include statement for

the new Rectangle.h

Create a Rectangle object

and call its methods.

We’ll do this together…

Page 102: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Special methods

There are several methods that deal with creating and

destroying objects.

These include: Constructors – called when an object is created. Can have many defined per class.

Destructor – one per class, called when an object is destroyed

Copy – called when an object is created by copying an existing object

Move – a feature of C++11 that is used in certain circumstances to avoid copies.

Page 103: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Construction and Destruction

The constructor is called when an

object is created.

This is used to initialize an object:

Load values into member variables

Open files

Connect to hardware, databases,

networks, etc.

The destructor is called when an

object goes out of scope.

Example:

Object c1 is created when the

program reaches the first line of

the function, and destroyed when

the program leaves the function.

void function() {

ClassOne c1 ;

}

Page 104: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

When an object is instantiated…

The rT object is created in memory.

When it is created its constructor is called to

do any necessary initialization.

The constructor can take any number of

arguments like any other function but it

cannot return any values.

What if there are multiple constructors? The compiler follows standard function overload rules. Note the constructor

has no return type!

Page 105: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

A second constructor

rectangle.h

class Rectangle

{

public:

Rectangle();

Rectangle(const float width,

const float length) ;

/* etc */

};

rectangle.cpp#include "rectangle.h“

/* C++11 style */

Rectangle::Rectangle(const float width,

const float length):

m_width(width),

m_length(length)

{

/* extra code could go here */

}

Adding a second constructor is similar to overloading a

function.

Here the modern C++11 style is used to set the member

values – this is called a member initialization list

Page 106: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Member Initialization Lists

Syntax:

MyClass(int A, OtherClass &B, float C):

m_A(A),

m_B(B),

m_C(C) {

/* other code can go here */

}

Colon goes here

Members assigned

and separated with

commas. The order

doesn’t matter.

Additional code can be

added in the code

block.

Page 107: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

And now use both constructors

Both constructors are now used.

The new constructor initializes the

values when the object is created.

Constructors are used to:

Initialize members

Open files

Connect to databases

Etc.

#include <iostream>

using namespace std;

#include "Rectangle.h“

int main(int argc, char** argv)

{

Rectangle rT ;

rT.m_width = 1.0 ;

rT.m_length = 2.0 ;

cout << rT.Area() << endl ;

Rectangle rT_2(2.0,2.0) ;

cout << rT_2.Area() << endl ;

return 0;

}

Page 108: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Default values

C++11 added the ability to define default

values in headers in an intuitive way.

Pre-C++11 default values would have been

coded into constructors.

If members with default values get their value

set in constructor than the default value is

ignored.

i.e. no “double setting” of the value.

class Rectangle {

public:

Rectangle();

Rectangle(const float width,

const float length) ;

Rectangle(const Rectangle& orig);

virtual ~Rectangle();

float m_length = 0.0 ;

float m_width = 0.0 ;

float Area() ;

float ScaledArea(const float scale);

private:

};

Page 109: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Default constructors and destructors

The two methods created by Eclipse automatically

are explicit versions of the default C++ constructors

and destructors.

Every class has them – if you don’t define them then

empty ones that do nothing will be created for you by

the compiler.

If you really don’t want the default constructor you can

delete it with the delete keyword.

Also in the header file you can use the default keyword

if you like to be clear that you are using the default.

class Foo {

public:

Foo() = delete ;

// Another constructor

// must be defined!

Foo(int x) ;

};

class Bar {

public:

Bar() = default ;

};

Page 110: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Custom constructors and destructors

You must define your own constructor when you want to initialize an

object with arguments.

A custom destructor is always needed when internal members in the

class need special handling.

Examples: manually allocated memory, open files, hardware drivers, database or

network connections, custom data structures, etc.

Page 111: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Destructors

Destructors are called when an object is

destroyed.

Destructors have no return type.

There is only one destructor allowed per

class.

Objects are destroyed when they go out

of scope.

Destructors are never called explicitly by

the programmer. Calls to destructors are

inserted automatically by the compiler.

Rectangle::~Rectangle()

{

}

This class just has 2 floats as members which are

automatically removed from memory by the compiler.

House object

~House() destructor

Page 112: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Destructors

Example:

class Example {

public:

Example() = delete ;

Example(int count) ;

virtual ~Example() ;

// A pointer to some memory

// that will be allocated.

float *values = nullptr ;

};

Example::Example(int count) {

// Allocate memory to store "count"

// floats.

values = new float[count];

}

Example::~Example() {

// The destructor must free this

// memory. Only do so if values is not

// null.

if (values) {

delete[] values ;

}

}

Page 113: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Scope Scope is the region where a variable is valid.

Constructors are called when an object is created.

Destructors are only ever called implicitly.

int main() { // Start of a code block

// in main function scope

float x ; // No constructors for built-in types

ClassOne c1 ; // c1 constructor ClassOne() is called.

if (1){ // Start of an inner code block

// scope of c2 is this inner code block

ClassOne c2 ; //c2 constructor ClassOne() is called.

} // c2 destructor ~ClassOne() is called.

ClassOne c3 ; // c3 constructor ClassOne() is called.

} // leaving program, call destructors for c3 and c1 ~ClassOne()

// variable x: no destructor for built-in type

Page 114: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Copy, Assignment, and Move Constructors

The compiler will automatically create constructors to deal with copying, assignment, and

moving. NetBeans filled in an empty default copy constructor for us.

How do you know if you need to write one?

When the code won’t compile and the error message says you need one!

OR unexpected things happen when running.

You may require custom code when...

dealing with open files inside an object

The class manually allocated memory

Hardware resources (a serial port) opened inside an object

Etc.

Rectangle rT_1(1.0,2.0) ;

// Now use the copy constructor

Rectangle rT_2(rT_1) ;

// Do an assignment, with the

// default assignment operator

rT_2 = rT_1 ;

Page 115: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Templates and classes

Classes can also be created via templates in C++

Templates can be used for type definitions with: Entire class definitions

Members of the class

Methods of the class

Templates can be used with class inheritance as well.

This topic is way beyond the scope of this tutorial!

Page 116: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Inheritance

Inheritance is the ability to form a

hierarchy of classes where they

share common members and

methods. Helps with: code re-use, consistent

programming, program organization

This is a powerful concept!

Molecule

Inorganic

Mineral

Organic

Protein

Page 117: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Inheritance The class being derived from is referred

to as the base, parent, or super class.

The class being derived is the derived,

child, or sub class.

For consistency, we’ll use superclass

and subclass in this tutorial. A base class

is the one at the top of the hierarchy.

Molecule

Inorganic

Mineral

Organic

Protein

Superclass

Subclass

Base Class

Page 118: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Inheritance in Action

Streams in C++ are series of characters

– the C+ I/O system is based on this

concept.

cout is an object of the class ostream. It

is a write-only series of characters that

prints to the terminal.

There are two subclasses of ostream:

ofstream – write characters to a file

ostringstream – write characters to a string

Writing to the terminal is straightforward:

cout << some_variable ;

How might an object of class ofstream or

ostringstream be used if we want to write

characters to a file or to a string?

Page 119: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Inheritance in Action

For ofstream and ofstringstream the << operator is inherited from ostream

and behaves the same way for each from the programmer’s point of view.

The ofstream class adds a constructor to open a file and a close() method.

ofstringstream adds a method to retrieve the underlying string, str()

If you wanted a class to write to something else, like a USB port… Maybe look into inheriting from ostream!

Or its underlying class, basic_ostream which handles types other than characters…

Page 120: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Inheritance in Action

#include <iostream> // cout

#include <fstream> // ofstream

#include <sstream> // ostringstream

using namespace std ;

void some_func(string msg) {

cout << msg ; // to the terminal

// The constructor opens a file for writing

ofstream my_file("filename.txt") ;

// Write to the file.

my_file << msg ;

// close the file.

my_file.close() ;

ostringstream oss ;

// Write to the stringstream

oss << msg ;

// Get the string from stringstream

cout << oss.str() ;

}

Page 121: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

VTK - A C++ library for graphics and image processing.

The VTK documentation has inheritance

diagrams.

Let’s look at two classes, vtkPNGWriter

and vtkPNGReader.

https://vtk.org/doc/nightly/html/classvtkPNGWriter.html

https://vtk.org/doc/nightly/html/classvtkPNGReader.html

Page 122: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Public, protected, private

Public and protrected canbe

added to the Rectangle class.

These are used to control access

to parts of the class with

inheritance.

class Rectangle

{

public:

Rectangle();

Rectangle(float width, float length) ;

virtual ~Rectangle();

float m_width ;

float m_length ;

float Area() ;

protected:

private:

};

“There are only two things wrong with C++: The initial concept

and the implementation.”

– Bertrand Meyer (inventor of the Eiffel OOP language)

Page 123: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

C++ Access Control and Inheritance

Access public protected private

Same class Yes Yes Yes

Subclass Yes Yes No

Outside classes Yes No No

Sub myobj ;

Myobj.i = 10 ; // public - ok

Myobj.j = 3 ; // protected - Compiler error

Myobj.k = 1 ; // private - Compiler error

class Super {

public:

int i;

protected:

int j ;

private:

int k ;

};

class Sub : public Super {

// in methods, could access

// i and j from Parent only.

};

Inheritance

Outside code

Page 124: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Inheritance

With inheritance subclasses have access

to private and protected members and

methods all the way back to the base

class.

Each subclass can still define its own

public, protected, and private members

and methods along the way.

class A

public

protected

private

class B : public A

public

protected

private

public A

protected A

class C : public B

public A

protected A

public

protected

public B

protected B

private

Page 125: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Single vs Multiple Inheritance

C++ supports creating relationships where a subclass

inherits data members and methods from a single

superclass: single inheritance

C++ also support inheriting from multiple classes

simultaneously: Multiple inheritance

This tutorial will only cover single inheritance.

Generally speaking…

Multiple inheritance requires a large amount of design effort

It’s an easy way to end up with overly complex, fragile code

Java and C# (both came after C++) exclude multiple

inheritance on purpose to avoid problems with it.

With multiple inheritance a hierarchy like

this is possible to create…this is

nicknamed the Deadly Diamond of

Death.

D

B C

A

Page 126: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

C++ Inheritance Syntax

Inheritance syntax pattern:class SubclassName : public SuperclassName

Here the public keyword is used. Methods implemented in class Sub can access any public or

protected members and methods in Super but cannot access

anything that is private.

Other inheritance types are protected and private.

class Super {

public:

int i;

protected:

int j ;

private:

int k ;

};

class Sub : public Super {

// ...

};

Page 127: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Square

Let’s make a subclass of Rectangle called Square.

Open the Eclipse project Shapes

This has the Rectangle class from Part 2 implemented.

Add a class named Square.

Make it inherit from Rectangle.

Page 128: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Class Square inherits from class Rectangle

Square.h Square.cpp

#ifndef SQUARE_H

#define SQUARE_H

#include "Rectangle.h"

class Square : public Rectangle

{

public:

Square();

virtual ~Square();

protected:

private:

};

#endif // SQUARE_H

#include “Square.h"

Square::Square()

{}

Square::~Square()

{}

Note that subclasses are free to add any number

of new methods or members, they are not limited

to those in the superclass.

Page 129: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

A new Square constructor is needed.

A square is, of course, just a rectangle with equal length and width.

The area can be calculated the same way as a rectangle.

Our Square class therefore needs just one value to initialize it and it can

re-use the Rectangle.Area() method for its area.

Go ahead and try it:

Add an argument to the default constructor in Square.h

Update the constructor in Square.cpp to do…?

Remember Square can access the public members and methods in its superclass

Page 130: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Solution 1

Square can access the public members in its superclass.

Its constructor can then just assign the length of the side to the

Rectangle m_width and m_length.

This is unsatisfying – while there is nothing wrong with this it’s

not the OOP way to do things.

Why re-code the perfectly good constructor in Rectangle?

#ifndef SQUARE_H

#define SQUARE_H

#include “Rectangle.h"

class Square : public Rectangle

{

public:

Square(float width);

virtual ~Square();

protected:

private:

};

#endif // SQUARE_H

#include “Square.h"

Square::Square(float length):

m_width (length), m_length(length)

{

}

Page 131: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

The delegating constructor

C++11 added a new constructor type

called the delegating constructor.

Using member initialization lists you can

call one constructor from another.

Even better: with member initialization

lists C++ can call superclass

constructors!

Square::Square(float length) :

Rectangle(length,length)

{

// other code could go here.

}

class class_c {

public:

int max;

int min;

int middle;

class_c(int my_max) {

max = my_max > 0 ? my_max : 10;

}

class_c(int my_max, int my_min) : class_c(my_max) {

min = my_min > 0 && my_min < max ? my_min : 1;

}

class_c(int my_max, int my_min, int my_middle) :

class_c (my_max, my_min){

middle = my_middle < max &&

my_middle > min ? my_middle : 5;

}

};

Reference: https://msdn.microsoft.com/en-us/library/dn387583.aspx

Page 132: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Solution 2

Square can directly call its superclass constructor and let the

Rectangle constructor make the assignment to m_width and

m_length.

This saves typing, time, and reduces the chance of adding

bugs to your code.

The more complex your code, the more compelling this statement

is.

Code re-use is one of the prime reasons to use OOP.

#ifndef SQUARE_H

#define SQUARE_H

#include "Rectangle.h"

class Square : public Rectangle

{

public:

Square(float width);

virtual ~Square();

protected:

private:

};

#endif // SQUARE_H

#include "Square.h"

Square::Square(float length) :

Rectangle(length, length) {}

Page 133: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Trying it out in main()

What happens behind the scenes

when this is compiled….

#include <iostream>

using namespace std;

#include “Square.h"

int main()

{

Square sQ(4) ;

// Uses the Rectangle Area() method!

cout << sQ.Area() << endl ;

return 0;

}

sQ.Area()

Square class does not

implement Area() so compiler looks

to superclass

Finds Area() in Rectangle class.

Inserts call to Rectangle.Area()

method in compiled code.

Page 134: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

More on Destructors When a subclass object is

removed from memory, its

destructor is called as it is for any

object.

Its superclass destructor is than

also called .

Each subclass should only clean

up its own problems and let

superclasses clean up theirs.

Square object is removed from

memory

~Square() is called

~Rectangle() is called

Page 135: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

The formal concepts in OOPPolymorphism

Encapsulation

Inheritance

Abstraction

OOP

Next up: Polymorphism

Page 136: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Using subclasses A function that takes a superclass

argument can also be called with

a subclass as the argument.

The reverse is not true – a

function expecting a subclass

argument cannot accept its

superclass.

Copy the code to the right and

add it to your main.cpp file.

void PrintArea(Rectangle &rT) {

cout << rT.Area() << endl ;

}

int main() {

Rectangle rT(1.0,2.0) ;

Square sQ(3.0) ;

PrintArea(rT) ;

PrintArea(sQ) ;

}

The PrintArea function

can accept the Square

object sQ because

Square is a subclass of

Rectangle.

Page 137: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Overriding Methods Sometimes a subclass needs to have the

same interface to a method as a

superclass but with different functionality.

This is achieved by overriding a method.

Overriding a method is simple: just re-

implement the method with the same

name and arguments in the subclass.

class Super {

public:

void PrintNum() {

cout << 1 << endl ;

}

} ;

class Sub : public Super {

public:

// Override

void PrintNum() {

cout << 2 << endl ;

}

} ;

Super sP ;

sP.PrintNum() ; // Prints 1

Sub sB ;

sB.PrintNum() ; // Prints 2

Page 138: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Overriding Methods

Seems simple, right?

class Super {

public:

void PrintNum() {

cout << 1 << endl ;

}

} ;

class Sub : public Super {

public:

// Override

void PrintNum() {

cout << 2 << endl ;

}

} ;

Super sP ;

sP.PrintNum() ; // Prints 1

Sub sB ;

sB.PrintNum() ; // Prints 2

Page 139: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

How about in a function call…

Using a single function to operate

on different types is

polymorphism.

Given the class definitions, what

is happening in this function call?

class Super {

public:

void PrintNum() {

cout << 1 << endl ;

}

} ;

class Sub : public Super {

public:

// Override

void PrintNum() {

cout << 2 << endl ;

}

} ;

void FuncRef(Super &sP) {

sP.PrintNum() ;

}

Super sP ;

Func(sP) ; // Prints 1

Sub sB ;

Func(sB) ; // Hey!! Prints 1!!

“C++ is an insult to the human brain”

– Niklaus Wirth (designer of Pascal)

Page 140: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Type casting

The Func function passes the argument as a reference (Super &sP).

What’s happening here is dynamic type casting, the process of converting from

one type to another at runtime.

Same mechanism as the dynamic_cast<type>() function

The incoming object is treated as though it were a superclass object in

the function.

When methods are overridden and called there are two points where

the proper version of the method can be identified: either at compile

time or at runtime.

void FuncRef(Super &sP) {

sP.PrintNum() ;

}

Page 141: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Virtual methods When a method is labeled as virtual and

overridden the compiler will generate

code that will check the type of an object

at runtime when the method is called.

The type check will then result in the

expected version of the method being

called.

When overriding a virtual method in a

subclass, it’s a good idea to label the

method as virtual in the subclass as well.

…just in case this gets subclassed again!

class SuperVirtual

{

public:

virtual void PrintNum()

{

cout << 1 << endl ;

}

} ;

class SubVirtual : public SuperVirtual

{

public:

// Override

virtual void PrintNum()

{

cout << 2 << endl ;

}

} ;

void Func(SuperVirtual &sP)

{

sP.PrintNum() ;

}

SuperVirtual sP ;

Func(sP) ; // Prints 1

SubVirtual sB ;

Func(sB) ; // Prints 2!!

Page 142: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Early (static) vs. Late (dynamic) binding

Leaving out the virtual keyword on a

method that is overridden results in the

compiler deciding at compile time which

version (subclass or superclass) of the

method to call.

This is called early or static binding.

At compile time, a function that takes a

superclass argument will only call the

non-virtual superclass method under

early binding.

Making a method virtual adds code

behind the scenes (that you, the

programmer, never interact with directly)

Lookups in a hidden table, called the

vtable, are done to figure out what version

of the virtual method should be run.

This is called late or dynamic binding.

There is a small performance penalty for

late binding due to the vtable lookup.

This only applies when an object is

referred to by a reference or pointer.

Page 143: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Behind the scenes – vptr and vtable

C++ classes have a hidden pointer (vptr)

generated that points to a table of virtual

methods associated with a class (vtable).

When a virtual class method (base class

or its subclasses) is called by reference (

or pointer) when the program is running

the following happens:

The object’s class vptr is followed to its class

vtable

The virtual method is looked up in the vtable

and is then called.

One vptr and one vtable per class so minimal

memory overhead

If a method override is non-virtual it won’t be in

the vtable and it is selected at compile time.

Func(SuperVirtual &sP)

sP is a reference to a…

SuperVirtual SubVirtual

SuperVirtual’s

vptr

SubVirtual’s

vptr

Vtable

& SuperVirtual::PrintNum()

Vtable

& SubVirtual::PrintNum()

Page 144: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Let’s run this through the debugger

Open the project Virtual_Method_Calls.

Everything here is implemented in one big main.cpp

Place a breakpoint at the first line in main() and in the two

implementations of Func()

Page 145: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

When to make methods virtual

If a method will be (or might be)

overridden in a subclass, make it virtual

There is a minuscule performance

penalty. Will that even matter to you? i.e. Have you profiled and tested your code to

show that virtual method calls are a performance

issue?

When is this true? Almost always! Who knows how your code will

be used in the future?

Constructors are never virtual in C++.

Destructors in a base class should

always be virtual.

Also – if any method in a class is virtual,

make the destructor virtual

These are important when dealing with

objects via reference and it avoids some

subtleties when manually allocating

memory.

Page 146: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Why all this complexity?

Late binding allows for code libraries to be updated for new functionality. As methods are identified

at runtime the executable does not need to be updated.

This is done all the time! Your C++ code may be, for example, a plugin to an existing simulation

code.

Greater flexibility when dealing with multiple subclasses of a superclass.

Most of the time this is the behavior you are looking for when building class hierarchies.

void FuncLate(SuperVirtual sP)

{

sP.PrintNum() ;

}

void FuncEarly(SuperVirtual &sP)

{

sP.PrintNum() ;

}

Called by reference – late binding

to PrintNum() Called by value – early binding to

PrintNum even though it’s virtual!

Page 147: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Remember the Deadly Diamond of

Death? Let’s explain.

Look at the class hierarchy on the right.

Square and Circle inherit from Shape

Squircle inherits from both Square and Circle

Syntax:

class Squircle : public Square, public Circle

The Shape class implements an empty

Area() method. The Square and Circle

classes override it. Squircle does not.

Under late binding, which version of Area

is accessed from Squircle?

Square.Area() or Circle.Area()?

Shape

virtual float Area() {}

Square

virtual float

Area() {…}

Circle

virtual float

Area() {…}

Squircle

Page 148: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Interfaces

Interfaces are a way to have your

classes share behavior without them

sharing actual code.

Gives much of the benefit of multiple

inheritance without the complexity and

pitfalls

Shape

Square Circle

Example: for debugging you want each class

to have a Log() method that writes some info

to a file.

Implement with an interface.

Log

Page 149: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Interfaces

An interface class in C++ is called a pure virtual class.

It contains virtual methods only with a special syntax.

Instead of {} the function is set to 0. Any subclass needs to implement the methods!

Modified Square.h shown.

What happens when this is compiled?

Once the LogInfo() is uncommented it will compile.

#ifndef SQUARE_H

#define SQUARE_H

#include "rectangle.h"

class Log {

virtual void LogInfo()=0 ;

};

class Square : public Rectangle, Log

{

public:

Square(float length);

virtual ~Square();

// virtual void LogInfo() {}

protected:

private:

};

#endif // SQUARE_H

(…error…)

include/square.h:10:7: note: because the following virtual

functions are pure within 'Square':

class Square : public Rectangle, Log

^

include/square.h:7:18: note: virtual void Log::LogInfo()

virtual void LogInfo()=0 ;

Page 150: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Putting it all together

Now let’s revisit our Shapes

project.

Open the “Shapes with Circle”

project.

This has a Shape base class with a

Rectangle and a Square

Add a Circle class to the class

hierarchy in a sensible fashion.

Shape

Rectangle

Square

Hint: Think first, code second.

Circle

???

Page 151: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

New pure virtual Shape class

Slight bit of trickery:

An empty constructor is defined in shape.h

No need to have an extra shape.cpp file if these

functions do nothing!

Q: How much code can be in the header file?

A: Most of it with some exceptions.

.h files are not compiled into .o files so a

header with a lot of code gets re-compiled

every time it’s referenced in a source file.

#ifndef SHAPE_H

#define SHAPE_H

class Shape

{

public:

Shape() {}

virtual ~Shape() {}

virtual float Area()=0 ;

protected:

private:

};

#endif // SHAPE_H

Page 152: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Give it a try

Add inheritance from Shape

to the Rectangle class

Add a Circle class, inheriting

from wherever you like.

Implement Area() for the

Circle

If you just want to see a

solution, open the project

“Shapes with Circle solved”

Page 153: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

A Potential Solution

A Circle has one dimension

(radius), like a Square.

Would only need to override the

Area() method

But…

Would be storing the radius in the

members m_width and m_length.

This is not a very obvious to

someone else who reads your code.

Maybe:

Change m_width and m_length

names to m_dim_1 and m_dim_2?

Just makes everything more muddled!

Shape

Rectangle

Square

Circle

Page 154: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

A Better Solution

Inherit separately from the Shape

base class

Seems logical, to most people a

circle is not a specialized form of

rectangle…

Add a member m_radius to store

the radius.

Implement the Area() method

Makes more sense!

Easy to extend to add an Oval

class, etc.

Shape

Rectangle

Square

Circle

Page 155: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

New Circle class

Also inherits from Shape

Adds a constant value for p

Constant values can be defined right in the

header file.

If you accidentally try to change the value of PI

the compiler will throw an error.

#ifndef CIRCLE_H

#define CIRCLE_H

#include "shape.h"

class Circle : public Shape

{

public:

Circle();

Circle(float radius) ;

virtual ~Circle();

virtual float Area() ;

const float PI = 3.14;

float m_radius ;

protected:

private:

};

#endif // CIRCLE_H

Page 156: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

circle.cpp

Questions?

#include "circle.h"

Circle::Circle()

{

//ctor

}

Circle::~Circle()

{

//dtor

}

// Use a member initialization list.

Circle::Circle(float radius) : m_radius{radius}

{}

float Circle::Area()

{

// Quiz: what happens if this line is

// uncommented and then compiled:

//PI=3.14159 ;

return m_radius * m_radius * PI ;

}

Page 157: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Quiz time!

What happens behind

the scenes when the

function PrintArea is

called?

How about if PrintArea’s

argument was instead:

void PrintArea(Shape shape)

void PrintArea(Shape &shape) {

cout << "Area: " << shape.Area() << endl ;

}

int main()

{

Square sQ(4) ;

Circle circ(3.5) ;

Rectangle rT(21,2) ;

// Print everything

PrintArea(sQ) ;

PrintArea(rT) ;

PrintArea(circ) ;

return 0;

}

Page 158: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Quick mention…

Aside from overriding functions it

is also possible to override

operators in C++.

As seen in the C++ string. The +

operator concatenates strings:

It’s possible to override +,-,=,<,>,

brackets, parentheses, etc.

Syntax:

Recommendation:

Generally speaking, avoid this. This

is an easy way to generate very

confusing code.

A well-named function will almost

always be easier to understand than

an operator.

An exceptions is the assignment

operator: operator=

string str = "ABC" ;

str = str + "DEF" ;

// str is now "ABCDEF"

MyClass operator*(const MyClass& mC) {...}

Page 159: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Summary

C++ classes can be created in hierarchies via

inheritance, a core concept in OOP.

Classes that inherit from others can make use

of the superclass’ public and protected

members and methods

You write less code!

Virtual methods should be used

whenever methods will be overridden in

subclasses.

Avoid multiple inheritance, use interfaces

instead.

Subclasses can override a superclass

method for their own purposes and can still

explicitly call the superclass method.

Abstraction means hiding details when they

don’t need to be accessed by external code. Reduces the chances for bugs.

While there is a lot of complexity here – in

terms of concepts, syntax, and application –

keep in mind that OOP is a highly successful

way of building programs!

Page 160: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

A high quality random number generator

The motivation for this code can be found on the RCS

website: http://rcs.bu.edu/examples/random_numbers/

The RNG implemented here is the xoroshiro128+ algorithm.

The inventors published a C implementation on their

website:

http://xoshiro.di.unimi.it/

Page 161: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Some OOP Guidelines

Here are some guidelines for putting together a program using OOP to keep in mind while getting

up and running with C++.

Keep your classes simple and single

purpose.

Logically organize your classes to re-use

code via inheritance.

Use interfaces in place of multiple

inheritance

Keep your methods short

Many descriptive methods that do little things

is easier to debug and understand.

Follow the KISS principle:

“Keep it simple stupid”

“Keep it simple, silly”

“Keep it short and sweet”

“Make Simple Tasks Simple!” – Bjarne

Stroustroup

“Make everything as simple as possible, but

not simpler” – Albert Einstein

Page 162: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Putting your classes together

Effective use of OOP demands that the programmer think/plan/design first and code second.

There is a large body of information on this topic:

As this is an academic institution your code may: Live on in your lab long after you have graduated

Be worked on by multiple researchers

Adapted to new problems you haven’t considered

Be shared with collaborators

For more structured environments (ex. a team of professional programmers) there exist concepts

like SOLID: https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)

…and there are many others.

Page 163: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Keep your classes simple

Avoid “monster” classes that implement everything including the kitchen sink.

Our Rectangle class just holds dimensions and calculates its area.

It cannot print out its area, send email, draw to the screen, etc.

Resource Allocation Is Initialization (RAII):

A late 80’s concept, widely used in OOP.

https://en.wikipedia.org/wiki/Resource_acquisiti

on_is_initialization

ALL Resources in a class are created in the

constructor and released in the destructor.

Example: opening files, allocating memory, etc.

If an object is created it is ready to use.

Single responsibility principle:

Every class has responsibility for one piece of functionality

in the program.

https://en.wikipedia.org/wiki/Single_responsibility_principle

Example:

An Image class holds image data and can read and write it

from disk.

A second class, ImageFilter, has methods that manipulate

Image objects and return new ones.

Page 164: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

C++ Libraries

There are a LOT of libraries available for

C++ code.

Sourceforge alone has >7400 https://sourceforge.net/directory/language:cpp/os:windows/?q=library

Before jumping into writing your code,

consider what you need and see if there

are libraries available.

Many libraries contain code

developed by professionals or

experts in a particular field.

Consider what you are trying to

accomplish in your research:

A) accomplishments in your field or

B) C++ programming?

Page 165: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

C++ Compilers on the SCC

There are 4 families of compilers on the SCC for C++. To see versions use the module avail command, e.g. module avail gnu

They have their strengths and weaknesses. For numeric code the intel and pgi

compilers tend to produce the fastest code.

For info on how to choose compiler optimizations for the SCC see the RCS website: http://www.bu.edu/tech/support/research/software-and-programming/programming/compilers/compiler-optimizations/

Module name Vendor Compiler Versions C++11 support

gnu GNU g++ 4.4.7 - 7.2.0 4.9.2 & up

intel Intel icpp 2016 – 2018 2017 & 2018

pgi Portland

Group /

Nvidia

pgc++ 13.5 – 18.4 18.4

llvm LLVM clang++ 3.9 – 6.0 All

Page 166: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Multithreading

OpenMP Open MP is a standard approach to writing multithreaded code to exploit multiple CPU cores

with your program.

Fully supported in C++

See http://www.openmp.org/ for details, or take an RCS tutorial on using it.

Intel Thread Building Blocks C++ specific library

Available on the SCC from Intel and is also open source.

Much more flexible and much more C++-ish than OpenMP

Offers high performance memory allocators for multithreaded code

Includes concurrent data types (vectors, etc.) that can automatically be shared amongst

threads with no added effort for the programmer to control access to them.

If you want to use this and need help: [email protected]

Page 167: Introduction to C++rcs.bu.edu/examples/cpp/tutorial/Introduction to C++.pdf · 2020. 9. 21. · A source file (file.cpp) contains the code that is compiled into an object file (file.o)

Math and Linear Algebra Eigen

http://eigen.tuxfamily.org/index.php?title=Main_Page

Available on the SCC.

“Eigen is a C++ template library for linear algebra: matrices, vectors, numerical solvers, and related algorithms.”

Armadillo http://arma.sourceforge.net/

Available on the SCC.

“Armadillo is a high quality linear algebra library (matrix maths) for the C++ language, aiming towards a good balance

between speed and ease of use. Provides high-level syntax (API) deliberately similar to Matlab.”

Also see matlab2cpp (https://github.com/jonathf/matlab2cpp), a semi-automatic tool for converting Matlab code to C++ with

Armadillo.

And also see PyJet (https://github.com/wolfv/pyjet), which converts Python and Numpy code to Armadillo/C++ code.

OpenCV https://opencv.org

A computer vision and image processing library, with excellent high-performance support for linear algebra, many

algorithms, and GPU acceleration.