710 likes | 722 Views
Concordia University Department of Computer Science and Software Engineering COMP345 Advanced Program Design with C++ Lecture 1: C++ basics. Learning Objectives. Introduction to C++ Shorthand notations Console Input/Output Program Style Libraries and Namespaces Separate compilation
E N D
Concordia UniversityDepartment of Computer Science and Software EngineeringCOMP345Advanced Program Design with C++Lecture 1: C++ basics
Learning Objectives • Introduction to C++ • Shorthand notations • Console Input/Output • Program Style • Libraries and Namespaces • Separate compilation • Preprocessor directives
Introduction to C++ • Why C++? • Although this course will cover programming practices in general, the focus will be on C++. • Why not Java? • C++ is more complex than Java. If you can write good programs in C++ well, you can transfer this skill to Java; the inverse is not true. • Although Java has achieved widespread popularity during the last ten years, there is still a need for C++ programmers. • Many games and most software for the telecommunications industry are written in C++.
Introduction to C++ • Companies that use C++ include: • Adobe products • Alias/Wavefront products (e.g., Maya) • Amazon • Google • JPL/NASA • Microsoft • There are many Java jobs and many Java programmers. There are not quite so many C++ jobs and there are very few good unemployed C++ programmers. Strong C++ programmers can find interesting and well-paid jobs.
Introduction to C++ • There exists an immense code base written in C/C++ that needs to be maintained. • Many companies have chosen C++, then developed extensive libraries in C++ for their internal use. Transferring to another language would require the translation of these libraries.
C++ origins • Low-level languages • Machine, assembly • High-level languages • C, C++, ADA, COBOL, FORTRAN • Object-Oriented-Programming
Some related languages • C: Direct ancestor of C++. Originally, C++ was to be backward compatible with C. Developed in the 1960-70s. • Simula : First operational object-oriented programming language, developed in the 1960s. • C# : A version of C++ that aims at simplification and removing of problematic features of C++. Runs using a virtual machine.
Structure of C++ programs • C++ Program • Main function and free functions (as in C) • Main function is the program driver • Classes encapsulate other functions (as in Java) • Programs may have header files (.h) and program files (.cpp) • Not necessary • No one-to-one relationship with classes as in Java
Characteristics of C++ • an evolution of C • procedural language • compiled execution mode with static/dynamic linking • high-level and low-level programming • static typing, with implicit/explicit casting mechanisms • object-oriented programming • multiple inheritance • pointers • generic programming: templates and virtual classes and functions • function/operator overloading • exception handling • namespaces
C++ Data types • Highly similar to Java data types • Basic types are not classes (also like Java) • Pit trap: different compilers will have different ranges for most basic data types • Some programs potentially will behave differently across different platforms • Hence, lack of portability of C++ programs • User-defined data types using struct (as in C), as well as class (object-oriented programming) • Both are allowed in the same program
Assigning Data • Initializing data in declaration statement • Results "undefined" if you don’t! • int myValue = 0; • Assigning data during execution • Lvalues (left-side) & Rvalues (right-side) • Lvalues must be variables • Rvalues can be any expression • Example:distance = rate * time;Lvalue: "distance"Rvalue: "rate * time"
Shorthand Notations Similar to Java
Data Assignment Rules • Compatibility of Data Assignments • Type mismatches • General Rule: Cannot place value of one type into variable of another type • intVar = 2.99; // 2 is assigned to intVar! • Only integer part "fits", so that’s all that goes • Called "implicit" or "automatic type conversion" • When using pointers, much more problematic! • Literals • 2, 5.75, ‘Z’, "Hello World“ • Considered "constants": can’t change in program • All literals have an inherent type
Type Casting static_cast<double>intVar • Explicitly "casts" or "converts" intVar to double type doubleVar = static_cast<double>intVar1/intVar2; • Casting forces double-precision division to take place among two integer variables
Type Casting • Two types of casting • Implicit type casting (type coercion) • Done for you, automatically17 / 5.5This expression causes an "implicit type cast" totake place, casting the 1717.0 • Explicit type casting • Programmer specifies conversion with cast operator(double)17 / 5.5Same expression as above, using explicit cast(double)myInt / myDouble
Type Casting • Kinds of explicit type casting: • static_cast<Type>(expression) • General-purpose type casting • const_cast<Type>(expression) • Cast-out “constantness” • dynamic_cast<Type>(expression) • Downcasting from a superclass to a subclass • reinterpret_cast<Type>(expression) • Implementation-dependent casting (not covered in this class)
Input/Output: streams • I/O objects cin, cout, cerr • Defined in the C++ library called<iostream> • Must have these lines (called pre-processor directives) near start of file: • #include <iostream>using namespace std; • Tells C++ to use appropriate library so we canuse the I/O objects cin, cout, cerr or • #include <iostream>using std::cout; • To include only the cout object
Console Output • What can be outputted? • Any data can be outputted to display screen • Variables • Constants • Literals • Expressions (which can include all of above) • cout << numberOfGames << " games played.";2 values are outputted: "value" of variable numberOfGames, literal string " games played.“ • cout is a stream, << is a stream operator to output to the stream. • Similar streams exist for file input/output.
Separating Lines of Output • New lines in output • Recall: "\n" is escape sequence for the char "newline" • A second method: object endl • Examples: cout << "Hello World\n"; • Sends string "Hello World" to display, & escapesequence "\n", skipping to next line cout << "Hello World" << endl; • Same result as above
Formatting Output • Formatting numeric values for output • Values may not display as you’d expect!cout << "The price is $" << price << endl; • If price (declared double) has value 78.5, you might get: • The price is $78.500000 or: • The price is $78.5 • We must explicitly tell C++ how to output specially-formatted numbers in our programs
Formatting Numbers • "Magic Formula" to force decimal sizes:cout.setf(ios::fixed);cout.setf(ios::showpoint);cout.precision(2); • These stmts force all future cout’ed values: • To have exactly two digits after the decimal place • Example:cout << "The price is $" << price << endl; • Now results in the following:The price is $78.50 • Can modify precision "as you go" as well
Error Output • Output with cerr • cerr works same as cout • Provides mechanism for distinguishingbetween regular output and error output
Input Using cin • cin for input (from the keyboard), cout for output (to the screen) • Differences: • ">>" (extraction operator) points opposite • Think of it as "pointing toward where the data goes" • Object name "cin" used instead of "cout" • No literals allowed for cin • Must input "to a variable" • cin >> num; • Waits on-screen for keyboard entry • Value entered at keyboard is "assigned" to num
Program Style • Bottom-line: Make programs easy to read and modify • Comments, two methods: • // Two slashes indicate entire line is to be ignored • /*Delimiters indicates everything between is ignored*/ • Identifier naming • ALL_CAPS for constants • lowerToUpper for variables • Most important: MEANINGFUL NAMES
Libraries • C++ Standard Libraries • #include <Library_Name> • Directive to "add" contents of library file toyour program • Called "preprocessor directive" • Executes before compiler, and simply "copies"library file into your program file • C++ has many libraries • Input/output, math, strings, etc.
Namespaces • Namespaces defined: • Collection of name definitions • For now: interested in namespace "std" • Has all standard library definitions we need • Examples:#include <iostream>using namespace std; • Includes entire standard library of name definitions • #include <iostream>using std::cin; using std::cout; • Can specify just the objects we want
Namespaces • Used to resolve name clashes • Programs use many classes, functions • Commonly have same names • Namespaces deal with this • Can be "on" or "off" • If names might conflict turn off
using Directive • using namespace std; • Makes all definitions in std namespaceavailable • Why might you NOT want this? • Can make cout, cin have non-standardmeaning • Perhaps a need to redefine cout, cin • Can redefine any others
Namespace std • We’ve used namespace std • Contains all names defined in many standard library files • Example:#include <iostream> • Places all name definitions (cin, cout, etc.)into std namespace • Program doesn’t know names • Must specify this namespace for programto access names
Global Namespace • All code goes in some namespace • Unless specified global namespace • No need for using directive • Global namespace always available • Implied "automatic" using directive
Multiple Names • Multiple namespaces • e.g., global, and std typically used • What if a name is defined in both? • Error • Can still use both namespaces • Must specify which namespace used atwhat time
Specifying Namespaces • Given namespaces NS1, NS2 • Both have void function myFunction()defined differently { using namespace NS1; myFunction();} { using namespace NS2; myFunction();} • using directive has block-scope
Creating a Namespace • Use namespace grouping:namespace Name_Space_Name{ Some_Code} • Places all names defined in Some_Codeinto namespace Name_Space_Name • Can then be made available:using namespace Name_Space_Name
Creating a Namespace • Function declaration:namespace Space1{ void greeting();} • Function definition:namespace Space1{ void greeting() { cout << "Hello from namespace Space1.\n"; }}
using Declarations • Can specify individual names from namespace • Consider:Namespaces NS1, NS2 existEach have functions fun1(), fun2() • Declaration syntax:using Name_Space::One_Name; • Specify which name from each:using NS1::fun1;using NS2::fun2;
using Definitions and Declarations • Differences: • using declaration • Makes ONE name in namespace available • Introduces names so no other uses of name are allowed • using directive • Makes ALL names in namespace available • Only "potentially" introduces names
Qualifying Names • Can specify where name comes from • Use "qualifier" and scope-resolution operator • Used if only intend one use (or few) • NS1::fun1(); • Specifies that fun() comes from namespaceNS1 • Especially useful for parameters:int getInput(std::istream inputStream); • Parameter found in istream’s std namespace • Eliminates need for using directive or declaration
Naming Namespaces • Include unique string • Like last name • Reduces chance of other namespaceswith same name • Often multiple programmers writenamespaces for same program • Must have distinct names • Without multiple definitions of same namein same scope • Results in error
Class Namespace Example: Display 11.6 Placing a Class in a Namespace (Header File)
Class Namespace Example: Display 11.7 Placing a Class in a Namespace (Implementation File)
Unnamed Namespaces • Compilation unit defined: • A file, along with all files #included in file • Every compilation unit has unnamed namespace • Written same way, but with no name • All names are then local to compilation unit • Use unnamed namespace to keep things "local" • Scope of unnamed namespace is compilation unit
Global vs. Unnamed Namespaces • Not same • Global namespace: • No namespace grouping at all • Global scope • Unnamed namespace: • Has namespace grouping, just no name • Local scope
Unnamed Namespace: example #include <iostream>using namespace std; namespace { const int i = 4; int variable; } int main() { cout << i << endl; variable = 100; return 0; }