coen244 programming methodology iiamer/teach/coen244/notes/topic01.pdfc a. amer introduction to c++...
TRANSCRIPT
COEN244Programming Methodology II
Aishy Amer
Electrical & Computer Engineering Concordia University
Lecture Outline:Course introductionIntroduction to C++
well-designed programs, Data types, Variable scope, Functions,Pointers, Arrays, struct, class, Header files, Name-spaces, ..
Principles of OOPSoftware Development MethodBooks, FAQ, ..
c© A. Amer COEN244: Introduction 1
Welcome to COEN244
COEN-244 emphasizes Object-Oriented Programming (OOP)methodologies and concepts of well-designed C++ programs
OOP: increasingly important both in academia & industry
C++: emerging as a language of choice
Because C++ combinesefficiency of C + the disciplined approach to software design
using interacting modules
Course prerequisites:
good understanding and experience
with functions, arrays, pointers, and i/o streams
C++ : very complex language → expect to work many hours
c© A. Amer COEN244: Introduction 2
Welcome to COEN244
To assist you:
Prof.: questions to C++ concepts
Tutors: questions to (practical) implementation and toassignments
PODs: questions to technical programming problems(view solutions to assignments)
Marker: questions to marking of assignments & quizzes
Help desk, helpdesk@encs: questions to computing facilities
COEN244 course website: announcements, course notes, etc.www.ece.concordia.ca/ amer/teach/coen244/
Email: Monitor your email for updates
c© A. Amer COEN244: Introduction 3
Ethics and Professionalism
Ethics: “Disciplined dealing with moral duty” &“System of right behavior”
Professionalism: “The conduct, aims, or qualities thatcharacterize a professional person”
Academic honesty: Cheating in any form not tolerated
Do not hesitate to ask questions
Be on time
No talking during class time
Respect deadlines
Personal emergency? Inform your Prof. ASAPc© A. Amer COEN244: Introduction 4
Ethics and Professionalism
Industry needs Engineers who..
Behave professionally: reliable, accept responsibility,...
Familiar with methodology of problems solving
Experienced in collaborating in a team
Complete problem solvers
Society needs Engineers who..
are both professional and socially responsible
c© A. Amer COEN244: Introduction 5
Ethics and Professionalism
A professional person
accepts responsibility fully & does not blame others for failure
is reliable - gets the job done on time
follows up on all the details
is respectful to others
has high standards of ethical behavior & does not lie or cheat
does not offer excuses in lieu of completed work
succeeds in spite of obstacles and road blocks
has justifiable self-confidence
...
c© A. Amer COEN244: Introduction 6
C++: What/why a computer program
Computers/Programs: tools to solve real-world problems
Solving real-world problems via programs?→ Simulation of real-world systems
System: well-defined arrangement of interacting processes witha common task
Process: act of transformation of information
Model: simplified representation of a system
Simulation: reproduction of selected aspects of systembehavior through experimentation based on the model
c© A. Amer COEN244: Introduction 7
C++: Well-designed programs
COEN244 focus: How to write well designed C++ programs
A well-designed program?
a combination of components (modules) that cooperate
to perform the common task but
are independent enough to be separately maintainable
A well designed program?
modular: classes and functions
general: can be applied for many applications/situations
maintainable: a code that the maintainer understand
c© A. Amer COEN244: Introduction 8
C++ overview
General form of a program: declarations & executable statements .....#include <iostream> // compiler directive
using namespace std;
float Quadratic(float,float,float,float); // function declaration
int main() {
float *a; float *b = new float; //variable declarations
a = new float(10); *b= 20; //executable statements
cout("a = %f ; b= %f\n",a,b);
delete a; delete b; // free memory!!
cout << Quadratic(*a,*b,); // function call
return 0;
}
float Quadratic(float x,float a,float b,float c) // implementation
{
float result;
result = a * x * x + b * x + c;
return result;
}
c© A. Amer Introduction to C++ 9
C++ overview
Variable Declaration: based on data type
Variable? int, char, struct, object, ..
Executable Statements:cout << "Enter the size of the fabric in square meters";
cost = tax_rate*price + price;
Reserved Words and Identifiers: cannot be used otherwise
Operators: binary, e.g., +, %, *, and unary, e.g., ++, !
Control structures: if/else, while, for, switch, ...
A compound statement: a group of statements enclosed by {}This block of code is treated as a single statement{} define a new program scope:its variables can be declared within these
c© A. Amer Introduction to C++ 10
C++ overview : Data types
Predefined Data Types: bool, char, float, string, ...
User-defined Data Types: class, struct, ...
int used for signed integer values (word size of the machine)also unsigned values
float used for 32 bit floating point values
double used for 64 bit double precision floating point values
char a one byte (signed) value (also unsigned char)
void can representnothing when used as the return type for a function oras a generic data type when used as the base type for apointer data type
c© A. Amer Introduction to C++ 11
C++ overview : Input/output
Input / output in C++I/O: a stream of consecutive bytes “from a source”/“to adestination”cin >> x; reads a (float) value from the standard input &stores it in xcout << len; writes the value of len to the standard output
c© A. Amer Introduction to C++ 12
C++ overview : Variable declaration
Variable declaration = a data type and a variable name
Data type can be:1. a basic type, except void2. an pointer type (including void *) or a reference type3. a struct or class
Variable name: start with letter or underscore (case sensitive)int i; <= integer
char *cPtr; <= pointer to a character
float arrayOfPoints[10]; <= array of 10 floats
unsigned char uc1, uc2, uc3; <= three separate unsigned characters.
void *genericPtr; <= indirect pointer to anything
A variable declaration can be placed anywhere in a program
c© A. Amer Introduction to C++ 13
C++ overview : Variable scope
Variable is known, or scoped:only within the program unit in which it was declared
Variable scope:local (function, compound statement)global: scoped within an entire programhas never been good practiceprivate (class)...
A variable declared outside of all functions in a file is accessibleby any code in that file
Data should not be directly visible to the outside worldGood practice: keep the scope of data as narrow as possible
c© A. Amer Introduction to C++ 14
C++ overview : Variable scope
Multiple file programs: variables declared in one file can bemade accessed by code in other files by specifying that it is anextern variable
extern declarations are often placed in an include fileIf there are multiple variables with the same name whose scopes overlap at one point in a
program, the variable with the innermost scope will be used
Any variable declared outside of all functions in a file can beaccessed by other files in the program by declaring the variableas extern in those other files
To declare variables as global within a file but they are to behidden from other program files:declare each of these variables as static
c© A. Amer Introduction to C++ 15
C++ overview : Variable scope
In file a.cc:
int anExternInt; // can be accessed by the file b.cc
static int aPrivateInt;
In file b.cc:
extern int anExternInt;
extern int aPrivateInt; // <= error was declared as static
A global variable is declared without the extern in only the filewith which the variable is most closely associated
It is then referenced with an extern, usually specified in aninclude file, in all other files that will use that variable
c© A. Amer Introduction to C++ 16
C++ overview : Constants
C++ supports the standard integer and floating point constants
Character constants can also be defined within ”: ’a’
A string constant: enclosing it between "":"COEN244 follows COEN243"
A constant string is an array of characters:its size = the number of characters in the string + 1
This extra byte at the end of the string stores a ’0’ (zero byte)considered as the terminator for the string
Most string functions assume that the zero byte terminator ispresent at the end of the string
c© A. Amer Introduction to C++ 17
C++ overview : Operators
Operators: binary, e.g., +, %, *, and unary, e.g., ++, !
* indirection operator: used to dereference a pointerprovide access to the data at that location
& address-of operator: used to get a pointer to a data item
() used to control the order evaluation of complex expressions
Expressions evaluation: according to the operators precedence
Every expression has a value resulting from its evaluation
C++ allows operators to be overloaded
c© A. Amer Introduction to C++ 18
C++ overview : Functions
C++ has only one subprogram unit called a function
Functions: function declaration and function implementation
Function definition: with formal parameters
Function call: replace formal parameters with actual parametersF. call that returns a value can be part of an expressionReturn type & formal parameter definition must be specifiedbefore the f. call
Function declaration: must define the data type for the formalparameters:used to check if usage correct
A function returns a value to the calling unit
c© A. Amer Introduction to C++ 19
C++ overview : Functions
The data type for the return value is specified in the functiondeclarationA void return type: does not return a valuefloat Quadratic(float,float,float,float); // declaration
float Quadratic(float x,float a,float b,float c)
{
float result;
result = a * x * x + b * x + c;
return result;
}
To maintain a variable value across function calls, declare thevariable as staticThis static is different than static to limit the scope of global variables
c© A. Amer Introduction to C++ 20
C++ overview : inline functions
inline Quadratic(float x,float a,float b,float c)
{
return a * x * x + b * x + c;
}
Use: the actual operation to be carried out by the function issmall (compared to the overhead of calling a function)
Speed up program execution
Parameter type checking is done but gain the faster executionas if you had written the code directly inline
c© A. Amer Introduction to C++ 21
C++ overview : Pointers
References: int i=5; int & r =i; //r alias to iA reference is an alternative name or alias for an objectAny operation carried out on r is then an operation on i
A reference must be initialized and cannot be changed torefer to another object
Pointers: a type of variable int* p;Value of a pointer is ?Every pointer has it own address
Linked list: a data structure where you get the practice to reallyunderstand pointers (see course website)
c© A. Amer Introduction to C++ 22
C++ overview : Pointers
Data types that give indirect access to an item
* is used to specify a pointer data typeis the address of an item of the specified data typeExample: int *, specifies a data type that is the address of an integer
& is used to specify a reference type& can be considered to create a new name (alias) for a dataExample: float &, an alias for a float item
& allows a variable to be accessed using the normal syntaxwhile the compiler handles the indirection for you
c© A. Amer Introduction to C++ 23
C++ overview: Pointers - ’NULL’ vs. ’\0’ Constant
int* pi = new int[100]; // allocate memory for 100 integers
if(pi == NULL) { // tests if allocation ok (pointer was created)
cout<< "Out of memory\n"; exit(0); // exit program
}
’NULL’ is a Named Constant for ’0’ pointer
Defined in iostream.h
In gcc/g++ compliers:it is not used as named constant for ’\0’ (null terminator)
Under Linux: use ’NULL’ as a substitute for 0 onlysee example above
null character (null terminator) ’\0’: a ASCII character with the value zero
in C++/C: it serves as a reserved character used to signify the end of a string
c© A. Amer Introduction to C++ 24
C++ overview : Arrays
int Asize=10;
float arrayOfPoints[Asize]; <= array of 10 floats
Array declaration: using [] with an integer size
Array of elements of any data typean array of char: char name[20];an array of struct: Student std[48];
Strings: arrays of type char, last element is ’0’
1D or 2D arrays
c© A. Amer Introduction to C++ 25
C++ overview : struct
struct is a way to create user-defined data types
struct has data members only (more later)
struct <struct_name> {
<struct data members> ;
};
----------------------------|-----------------------
struct Grade | struct Student
{ //Members of the struct | {
float assignments; | string name;
float quiz; | int id;
float midterm; | int GPA;
float final; | }
} |
----------------------------|--------------------------
Grade g; | Student s;
g.quiz = 9.7; | cin>> s.id;
cout << g.quiz; |
c© A. Amer Introduction to C++ 26
C++ overview: Classes
Object-oriented programming (OOP): software in a way thatmodels the real world
OOP: way of thinking oriented to objects
Real-world problems have objectsObjects define the problem
Class: an effective way to create user-defined data types
Class has both types of members: data and functions
A real-world problem: Automated banking system
Class BankAccount { // A Bank Account = a real object
Private Data:
int number; float balance;
Operations:
deposit(); withdraw();
};c© A. Amer Introduction to C++ 27
C++ overview: Classes
Differentiate: class implementation and class declaration
Class declaration: used by compiler to validate class use &are typically put in header files
Classes: bind data and operations together
class <class_name> {
public:
<member functions> ;
private:
<member data>
};
class Player {
public:
Player();
void move(); void attack(); void getBall();
private:
int health; int strength; int agility;
};
-----------------------------------------------
Player p,q; // p,q: objects of type Player;
// Player: class
p.move(); p.getBall(); //apply functions on p
c© A. Amer Introduction to C++ 28
C++ overview: Classes
class Cylinder { //class declaration in cylinder.h
private: //data
double radius, height; // data fields to access
public: //operations
void setCylinder(double r, double h); // set cylinder data
double getVolume() // compute volume
void scaleCylinder(double factor) // scale dimensions
void printCylinder() // print object state
};
// -------- Class implementation in cylinder.cpp
void Cylinder::setCylinder(double r, double h) // set cylinder data
{ radius = r; height = h; }
double Cylinder:: getVolume() // compute volume
{ return height * radius * radius * 3.141593; }
void Cylinder:: scaleCylinder(double factor) // scale dimensions
{ radius *= factor; height *= factor; }
void Cylinder:: printCylinder() // print object state
{ cout << "radius: " <<radius << " height: " <<height <<endl; }
==> Cylinder c,d; c.setCylinder(1.5,3.3);
c© A. Amer Introduction to C++ 29
C++ overview: Classes
Examples: Time, Date, Student, Vehicle, ...
describe a Vehicle?Vehicle is engine? Vehicle is red?
In practice: data members are private
Member functions which must be called from outside the class:public
Member functions which are only called from within the class:private
Each class has its own separate scope
c© A. Amer Introduction to C++ 30
C++ overview: Classes and objects
A class: A definition of something
A class: an entity that defines the attributes of an object
(Attributes: data and operations)
Object: an instance of a class
A bank Account is a class
A particular bank account (e.g., yours) is an object
c© A. Amer Introduction to C++ 31
C++ overview : Classes Hierarchy
Classes are organized in a hierarchy: base & derived classes
Define a new class similar to a predefined class:Bank-Account ⇐ Saving Account ⇐ International Account
The new class (derived class):similar to the original class (base class)but with additional attributes
Derived class inherits all attributes of a base class
c© A. Amer Introduction to C++ 32
C++ overview : Header files
Declarations (functions, struct, class) are placed intoa separate file, header file
It holds the external interface to the declarationsIt must be placed at start of any file that will use the declaration// in testComplex.cc
#include <stream.h> // a compiler directive
#include <stdlib.h> // a standard header file
#include "Complex.h" // a local (user-defined) header file
//as if the information in those files was directly typed here
int main() { ... }
#include<..> : compiler searches for the files in the "standard"directory
#include"..": compiler searches for the files in local directory& standard directory
c© A. Amer Introduction to C++ 33
C++ overview: Name-spaces
C++ supports modular programming through namespace
A namespace is a logical unit that contains related declarationsand definitions
namespace: symbol collections which are qualified by namesuch as types, variables, functions
It aims at avoiding name conflicts
using namespace X;
introduces all symbols in namespace X into the currentcontext without qualificationExample using namespace std;cin and cout are introduced
c© A. Amer Introduction to C++ 34
C++ overview: Namespaces
using X::y;
symbol y is introduced as being an abbreviation for X::ye.g. using std::iostream; −− > iostream introduced
You can create your own namespace
Example:namespace foo { void bar(); }
Call with:foo::bar() orusing namespace foo;bar();
Do not put using statements in header files
c© A. Amer Introduction to C++ 35
C++ overview: Namespaces
The namespace feature solve the problem of name conflicts:
When a team tries to link libraries provided by differentprogrammers the use of identical global identifiers will cause aname collision
The namespace feature surrounds the external declarationsof a library with a unique namespace that eliminates thepotentialfor such name conflicts
(The namespace solution assumes that two programmers do not usethe same namespace identifier!)
c© A. Amer Introduction to C++ 36
C++: some recommendation
Constant variable and functions: never modify
Type Casting:int(SomeNumber) (char*)i char*(i) //syntax error
nearly all safe conversions are implicit in C++
Explicit cast: something potentially dangerous
Logical errors
Example: An array index exceeds the array size
C++ environments: rich libraries → Do not re-invent the wheel
Use manual pages under Unix: man <command>
Example: man nint (rounding), man pow (power), man g++,
c© A. Amer Introduction to C++ 37
Principles of OOP: Client/Server model
A server:a class that provides services to objects or programsExample: the class Complex is a provider of services forComplex number processing functionalitiesaddComplex(...); printComplex(..); compareCircle(..)
A client:a class or program that uses the services (functionalities)of a server classa client requests services from a server (class) by invokingone of its functionsExample: c.setCylinder(..); x.addComplex(y);
c© A. Amer Principles of OOP 38
Principles of OOP: Client/Server model
Example: main() is the client of the server “Complex class”int main() {
Complex x,y,z;
z= x+y;
z.print(); z.isEqual(y);
...
}
A good server provides services with a minimum effortfrom the client
Implementation details are hidden from the client:it should not be required to know how the server provides theservices
c© A. Amer Principles of OOP 39
Principles of OOP
Pushing responsibility from client classes to server classes
Minimize coordination and communication among classes
Minimizing visibility of program elements to other programelements
Making program code self-explanatory
Functions versus classes:
Functions access the same data? Do they belong together?
C++ solution: binding together functions and data
Classes protect private data
C++ solution: private and public members
c© A. Amer Principles of OOP 40
Principles of OOP Software Development Method
ChallengeTremendous advances in hardware; slower comparableadvances in software
Software Engineering (SE): concerned with building largesoftware systems
Objectives of SE:Reliability: An unreliable life-critical system can be fatalUnderstandability: Future development very difficult ifsoftware is hard to understandCost Effectiveness: Cost to develop and maintain codeAdaptability: adaptive systems easier to alter and expandRe-usability: Improves reliability and maintainability, andreduces development costs
c© A. Amer Principles of OOP 41
Principles of OOP Software Development Method
Problem Analysis - (Correct Problem)
Identify data objectsGoal to model propertiesDetermine Input / Output dataConstraints on the problem
Design
Decompose into smaller problemsTop-down design (divide and conquer)Develop Algorithm (Desk check)
c© A. Amer Principles of OOP 42
Principles of OOP Software Development Method
Implementation : Writing the algorithm
Testing :
Verify the program meets requirementsSystem and Unit test
Documentation : Key part in the development process
c© A. Amer Principles of OOP 43
C++ Books, FAQ, ..
Richard Johnsonbaugh and Martin Kalin, Object-Oriented Programming in C++, 2nd Edition,Prentice Hall, 2000, 615 pages, ISBN: 0130158852.Effective C++ by Scott Meyers, 2005, ISBN 0321334876.Victor Shtern, Core C++: A Software Engineering Approach, Prentice Hall PTR, 2000, ISBN0-13-085729-7, 1237 pagesFrank Friedman and Elliot Koffman, Problem Solving, Abstraction, and Design Using C++, 3dedition, Addison-Wesley, 2000, ISBN 0-201-61277-1Paul Wang, Standard C++ with OOP, Brooks/Cole, ISBN 0-534-3731-0, 2000, 2d edition, 570pagesBjarne Stroustrup, The C++ Programming Language, AT&T, 1997Bjarne Stroustrup’s C++ web page and Glossary: http://www.research.att.com/ bs/C++.htmlErich Gamma, Richard Helm, Ralph Johnson, and John Vlissides,Design Patterns Elements of Reusable Object-Oriented Software,Addison Wesley Professional Computing Series, 1994, 416 pages, ISBN 0-201-63361-2C++ FAQ LiteReview of C++: http://ftp.cs.rochester.edu/ nelson/courses/csc_173/review
c© A. Amer Principles of OOP 44