41
Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file with a .h extension) files included in the compilation of a program. Usually contain types, definitions and declarations, but not executable code. Source file (file with a .cpp extension)

Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Embed Size (px)

Citation preview

Page 1: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Chapter 1 Introduction to C++:

Name space: Defines an area in which names have scope. Can use the same name in different name spaces.

Header file (file with a .h extension) files included in the compilation of a program. Usually contain types, definitions and declarations, but not executable code.

Source file (file with a .cpp extension)contains source code to be compiled.

Page 2: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Always back up source and header files (frequently)!!!Demo01.

Note that compiling a program creates very large files.

Also demo02shows how a gui can be set up. This will NOT be a focal point of the class.

Page 3: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Chapter 2 Numbers and objects:

Data typesfloat, int (32-bit in VC++ .NET), double (64-bit float)

Operators +, -, *, /, ++, --, %, etc. NOTE: Do not use % with negative integers; it’s different from the strict mathematic definition of % (modulus).

Page 4: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Most of this is similar to Java.More on cin, cout.

can input multiple nos with one cin but it’s not recommended.String input – does not read spaces.int input – make sure NOT to input a float number. The fractional part is ignored and remains in the buffer.endl is a newline for output streams.

Page 5: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

static casting – see page 49-50.const qualifier for variables. Always use in place of actual numbers. DO NOT USE magic numbers (p. 53).enumerated types

Similar to constant ints in java. See book example page 54.

Page 6: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Math functionsNeed: #include <cmath> for Visual studio. Might be #include <math.h> in other environments.See page 58 for math functions.

string types. Need #include <string>Demos have examples.See also p. 62-63.

Page 7: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Always initialize variables.Use meaningful variable names.Use // for short comments. Use /* and */ pair for lengthy or frequently changing comments.Always use a readable code layout.

Indent, format, use visual separators, align (code and output). See demos

Page 8: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Chapter 5 Designing and writing a class:

A class has two partsInterface (in a header file) and

implementation (in a cpp file).

Chapter 5 does not show this initially, but it should be done!

Page 9: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Interface: Variable definitions, constructors, and method signatures.

How the user interacts with the class.

Implementation: Code for the methods.

Page 10: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Method types:Every method identified in the interface must be defined in the implementation. See chapter 5 and demos for syntax.Mutator:

method that changes the object state.

Accessor: method that is not a Mutator. Should have a const qualifier (p. 239). See potential problem on p. 240.

Page 11: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

ConstructorsDefault constructor has no parameters. Examples on page 241. Or Build your own constructors with parameters (p. 244).

You should always write a default constructor!! They are used if a class variable is declared.Example, the following will NOT compile:

Page 12: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

#include <iostream>using namespace std;class Test{

public:Test (int value);int getdata(){

return data;}

private:int data;

};Test::Test(int value){ data = value;}int main(){

Test x;Test y(5);cout << x.getdata() << endl;cin.get();return 0;

}

Page 13: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

There are two possible solutions:Write a second constructor, Test::Test() and set data to a default value

Modify the above by writing Test::Test(int value = 0)

Page 14: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

NOTE: prose on page 241.

MUST initialize numeric data fields.

A string would automatically be instantiated as an empty string.

If the previous example also contained a string variable, it would NOT need to be specified in the parameter list.

Page 15: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

When two methods have the same name but different parameter sets, the function name is overloaded.

Page 16: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Caution: Consider the example

void funtest(int i, double d){ cout << "\n\nfuntest(int i, double d) called."; cout << "\nPar1 i = " << i << " ; Par2 d = " << d << endl;}void funtest(double d, int i){ cout << "\n\nfuntest(double d, int i) called."; cout << "\nPar1 d = " << d << " ; Par2 i = " << i << endl;}

Page 17: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Include the following in main. Show what happens when comments are removed. Why?funtest(1.2, 5);

funtest(3,5.5);

//funtest(4, 5);

Page 18: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Destructors.

Called when object goes out of scope.

Different from Java - you will need to write destructors.

Get in the habit of doing so now.

Page 19: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Same issues with private/public (encapsulation) as you saw in the Java courses. implicit and explicit parameters:

an explicit parameter is identified in the method name. An implicit parameter is the object specified when the method was called.

Page 20: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Accessors should always have a const qualifier.

Recall the example on page 240. DO NOT call a constructor for an object a second time.

i.e. do not explicitly invoke a constructor on an existing object.

CAN call constructors of other classes from a constructor (page 247-8). Elaborate on Advance Topic 5.1 (p. 247) and note the field initializer list.

Page 21: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Design the Investment class of Demo03.Section 5.8 discusses non-member functions, functions that are not members of any class. I will periodically use for illustrative purposes and sometimes in test harnesses. However, when using OOD, it’s best to NOT use them.Section 5.9 discusses header files.

Page 22: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Book Notes

Watch for missing and extraneous semicolons. Sometimes the compiler generates a message several lines beyond where it occurred. Do not mix >> and getline input commands.Do not mix << and printf output commands.See the random fact on p. 243.

Page 23: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Chapter 17 Exception Handling:

Exception: loose definition – a situation for which normal activities cannot proceed. Can be caused by: bad data, incorrect inputs, non-existent files, impossible tasks (divide by 0, square root of a negative number), etc.

Issues: Who must deal with them and how?

Page 24: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Book example

Stack class with methods: push, top, pop, and size. Designed by programmer P1Application that uses stack designed by programmer P2.What if there is an attempt to pop an empty stack and the application aborts?

Page 25: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

P1 provides the ability to check for it and argues P2 used the stack improperly.P2 argues P1 should have anticipated such problems.Stack class would be more reliable and robust if there were a better error checking mechanism.Programmers should not make assumptions regarding the user -- probably should also not make assumptions about other programmers who use their code.

Page 26: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

See quality Tip p. 669.Some traditional ways to deal with errors:

Printing error messages in certain conditions. Limited use: not always useful in production runs where there is no user watching the screen or real-time software where a user interaction takes too long.What if the user does not understand the language in which the message is printed?

Page 27: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Common examplemethod to calculate a square root displays a message if the incoming parameter is negative. This is a bad design.

flight controller error handler message

“incoming plane altitude too low – press enter to continue”

Page 28: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Using functions to return error codes. Of course, application must still check it. Also function may already be designed to return something (an object, for instance).See common error p. 671.External flags: See examples on page 672.

Page 29: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

What if you had y = sqrt(atoi(x)) where x is a string. Each of atoi and sqrt can generate a different errno? Another reason why global variables are not good.assert command.

Causes program to halt under certain conditions. This is not always desirable. See p. 673.

Page 30: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Error handler functionsUses a pointer to a function to handle errors when they occur. See p. 673 and code snippet from the next slide.

Page 31: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

#include <iostream>

using namespace std;

int eh1()

{ cout << "input is a negative number" << endl;

return 1;

}

int eh2()

{ cout << "input is 0" << endl;

return 2;

}

int (*test())()

{ float x;

cin >> x;

if (x==0)

{

return eh2;

}

if (x<0)

{

return eh1;

}

}

int main()

{ int (*f) ();

f = test();

(*f) ();

cin.get();

return 0;

}

Page 32: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Exception handling is the more accepted way of dealing with problems.Similar to Java exceptions. General form:

try{

code}catch (type1 e1){

code}catch (type2 e2){

code}:: catch (typen en){

code}

Somewhere in the try (or in methods called from the try there must be a throw exception command.

Page 33: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Example try/catch code below. logic_error(“string”) is a standard exception class declared in <stdexcept>.

float x;cin >> x;try{

if ( x < 0 )throw logic_error("negative value");

}catch (logic_error& e)

{cout << "Error: " << e.what() << endl;cin.get();exit (0);

}cout << sqrt(x) << endl; //don’t forget #include <cmath>cin.get();return 0;

Page 34: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Can throw and catch anything, but special error classes are typical Might look at example on p. 677, but don’t do this!Look at demo03 investment program with exceptions built into it. Note: two different types of exceptions (invalid numeric data and invalid characters in the input). Note also the locations of the throw instructions.

Page 35: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Can build derived exception classes from base exception classes. See standard exception hierarchy on p. 678. Demo03 has an alternative definition for the AppError class that is a derived class. Can change comments to use or remove it.Why do this? See p. 678.

Page 36: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Can use a catch clause using three dots (catch(…)) to mean “all remaining exceptions”.Note common error p. 682.If an exception is thrown AFTER dynamically creating memory the handler MUST remember to free it. Or else you have memory leaks!! This will be relevant later in this course!!

Page 37: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Can specify in method declaration exactly what exceptions a method can actually throw. See syntax on p. 686-7.Improper exception handling caused an ESA (European Space Agency) rocket to explode in 1996.See the quality tips and random facts on p. 687-8.

Page 38: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Where to catch and throw exceptions:

Example (sqrt method)Double sqrt(double x)

{

Try

{

if (x < 0)

Throw exception

}

Catch exception

{

Some logic

}

Page 39: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

What is wrong with this?Sqrt method is written to be used by others

Coder of sqrt is deciding what to do when exception is thrown.

In effect the coder is speaking for those who want to use the method.

Page 40: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Application may be calling sqrt for a value input from a keyboard. In that case may want to re-input.

for a value input from a file. In that case, may want to skip data.

for a value generated elsewhere. In that case, may want to perform alternative logic.

Page 41: Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file

Rule of thumb:Throw exception at the deepest level of program code as possible – at the very last possible place where the error must be checked

Catch the exception at the highest level possible – closest to the application that uses the code.

Let’s the user of the service decide what to do when errors occur.