CC++++: Some fundamental concepts: Some fundamental concepts
سعید امراللهی بیوکی[email protected]
v Prehistory of C++: C and Simula
v Template, Generic programming, C++ standard library organization
v C++ Class: Special member functions, Invariant and Operator Overloading
v C++0x: A brief introduction
PDF created with pdfFactory Pro trial version www.pdffactory.com
Is CIs C++++ dead?dead?• In 2003, the IDC reported well over 3,000,000 programmers full-time C++
programmers.
Maya PhotoShop
Google Search Engine
Mars RoverC# compiler
• Yes! You can’t learn to program without a programming language.
§ Is study of programming language important?
www.research.att.com/~bs/applications.html
Human Genome project
Doxygen
Acrobat Reader MySQL
Amazon.com iPod user interface
OS/400
Mozilla
OpenOffice
www.idc.org http://www.tiobe.com/tpci.htm
SymbianOS
PDF created with pdfFactory Pro trial version www.pdffactory.com
The Prehistory of CThe Prehistory of C++++: Simula and C: Simula and C
• Simula: Simulation – Data abstraction
- Class concept - (Flexible) Type system - Class hierarchy - Co-routine – Garbage collection - Concurrency
• C : System programming - Procedural programming
- machine-architecture-independent notions that directly map to the key hardware notions: pointer, array, …
Every C program should be a valid C++ program.
PDF created with pdfFactory Pro trial version www.pdffactory.com
C++ is a general-purpose programming language with a bias towards systems programming that
• is a better C• supports data abstraction• supports object-oriented programming• supports generic programming
• Many C++ design decisions have their roots in my dislike for forcing people to do things in some particular way.
- Bjarne Stroustrup
CC++++: A definition: A definition
Adding more and higher level of abstractions
Procedural programming OOP
GPFunctional
Programming ??
C++ 1978-1990 : Adding Simula features to C à C with ClassesC++: 1990-2008 à Template, Exceptions, Namespace, Generic programming,
STL, Template Meta-Programming, …C++: 2008- à Concepts, Lambda functions, threads, variadic templates,
initializer lists, rvalue references, tuples, regex, RNG, … à C++0xPDF created with pdfFactory Pro trial version www.pdffactory.com
Multiparadigm programmingMultiparadigm programming
• Abstraction mechanisms: functions, structures, concrete classes, abstract classes (interfaces), templates (classes & functions), concepts, …
• supports procedural programming• supports procedural programming• supports data abstraction• supports object-oriented programming• supports generic programming
C
Java
C++
• Even the simplest C++ program (Hello, world!) uses objects. cout is an object.
// Hello world in C++#include <iostream> int main(){
std::cout << “Hello, world\n”;}
C++ is a multi-paradigm programming language.
PDF created with pdfFactory Pro trial version www.pdffactory.com
The CThe C++++ classclass
class X { // The empty class};
class X {public:
X(); // Default constructorX(const X&); // Copy ConstructorX& operator=(const X&); // assignment operatorX* operator&(); // Address-of operator (non-const)const X* operator&() const;// Address-of operator (const)~X(); // Destructor: Cleanup
};
Provide as good support for user-defined types as for built-in types.
• C++ Language-technical rule:void f(){
int i;int j = i;j = i;
int* pi = &i;int* p = new int(0);// …delete p;
}
PDF created with pdfFactory Pro trial version www.pdffactory.com
Special member functionsSpecial member functions
• Constructor/Destructor: Resource acquisition/ release
void f(){
X x; // default ctorX y = x; // copy ctory = x; // copy assignment
X* px = &x; // address-ofX* p = new X(); // calling ctor// …delete p; // calling dtor
} // calling dtor of x and y implicitly
• Resource: Memory, File, Lock, Semaphore, Transactions, …
• The default constructor, copy constructor, copy assignment operator and destructor are special member functions.
• Copy constructor/Copy assignment operator: Initialization/Assignment
PDF created with pdfFactory Pro trial version www.pdffactory.com
ExamplesExamples
class DynArray { // dynamic arrayint* v;int size;
public:DynArray(int sz = 0) :
v(new int[size = sz]) { // initialize v } // memory allocatedDynArray(const DynArray&); DynArray& operator=(const DynArray&);~DynArray() { delete [] v; } // memory recycled (released)
};
class FileManager {std::ifstream f;
public:FileManager(const std::string& s) { f.open(s.c_str()); } // resource acquiredFileManager(const FileManager&);FileManager& operator=(const FileManager&);~FileManager() { f.close(); } // resource released
};
• Memory as resource
• File as resource
PDF created with pdfFactory Pro trial version www.pdffactory.com
Class InvariantsClass Invariants
Rob Murray:Representation Invariant: A Representation invariant is a predicate that is guaranteed to be true for every fully constructed object of the class.
• Object-Oriented: Avoid public data members.
• Constructor: establishment an invariant for the class.
class Address { // very commonpublic:
string GetCountry() const;void SetCountry(const string&);GetCity() const;void SetCity(const string&);// …
private:string Country;string City;string Street;// …
};
struct Address { // PODstring Country;string City;string Street;// …
};
Interface
Implementation
Abstraction
Encapsulation
public
• Invariant: a condition of the representation of an object (the object's state) that should hold each time an interface function is called.
Precondition &Postcondition
PDF created with pdfFactory Pro trial version www.pdffactory.com
Class Invariant: an exampleClass Invariant: an example
class Dollar { // invariant: <= 0 cents < 100public:
Dollar(int d, int c) : dollars(d), cents(c) {} // invariant may be invalidatedint GetDollars() const { return dollars; } int GetCents() const { return cents; }int GetAsCents() const { return dollars * 100 + cents; }void Add(const Dollar& d) { dollars += d.dollars; cents += d.cents; }void Add(int d, int c) { dollars += d; cents += c; }
private:int dollars, cents;
};
struct Dollar {Dollar(int d, int c) : dollars(d), cents(c) {}int dollars;int cents;
};void f(){
Dollar d(10, 30);d.dollars = 12; // fined.cents = 90; // fined.dollars -= 12; // d.Dollars = 0: fined.cents += 15; // d.Cents = 105; the invariant is broken!
}
• Invariant for Dollar class: cents must not be more than 99.
// invariant may be invalidated
PDF created with pdfFactory Pro trial version www.pdffactory.com
Invariant Invariant cont.cont.// check invariantbool Dollar::is_valid() const{
if(::abs(cents) > 99) return false;if((cents < 0) != (dollars < 0)) return false;
return true;}
class RangeError {// …
};
class Dollar { // invariant: <= 0 cents < 100public:
Dollar(int d, int c) : dollars(d), cents(c) {if (!is_valid()) throw RangeError(); // check invariant
}void Add(const Dollar& d) { dollars += d.dollars; cents += d.cents;
if (!is_valid()) throw RangeError(); // check invariant}void Add(int d, int c) { dollars += d; cents += c;
if (!is_valid()) throw RangeError(); // check invariant}
private:bool is_valid() const;int dollars, cents;
};
PDF created with pdfFactory Pro trial version www.pdffactory.com
Invariant and encapsulation Invariant and encapsulation cont.cont.class Complex {
double real, image;public:
Complex(double r = 0.0, double i = 0.0) : real_(r), image_(i) {}
double real() const { return real_; }double image() const { return image_; }void real(double r) { real_ = r; }void image(double i) { image_ = i; }
};
ρϴ
x
y
#include <cmath>class Complex { // change the representation
double r_, theta;public:
Complex(double r = 0.0, double i = 0.0) : r_(sqrt(r * r + i * i)), theta(atan(i/r)) {}
double real() const { return r_ * cos(theta); }double image() const { return r_ * sin(theta); }
void real(double r) { double y = r_ * sin(theta); r_= sqrt(r * r + y * y); theta = acos(r / r_); }
void image(double i) { double x = r_ * cos(theta); r_= sqrt( x * x + i * i); theta = asin(i / r_); }
};
PDF created with pdfFactory Pro trial version www.pdffactory.com
Class invariants Class invariants cont.cont.
• Date, Dollar, Rational number, Stack, String, Vector, … have invariant. They should be represented as a class.
• Address, Pair, Personal Record, … don’t have invariant. They are POD. It is better to represent them with struct.
• Stroustrup: Every class should have some invariant.
Classes should Enforce Invariants.
Destructor
ConstructorInitializes invariants.
Invalidates invariants.
PDF created with pdfFactory Pro trial version www.pdffactory.com
Operator overloadingOperator overloading
• Conventional shorthand notation- Complex arithmetic, Computer graphics, Linear algebra, Physics, String manipulation, …
• Overloading: having more than one name in the same scope.
Function overloading
Operator overloading
Overloading
Function name overloading
Operator functions
User
Designer/Implementer
Using overloaded operators is
easy!
Implementing overloaded operators is somehow difficult!
PDF created with pdfFactory Pro trial version www.pdffactory.com
Operator function: An exampleOperator function: An example
143 24 −++− xxx• Polynomials:
class Polynomial {public:
// member functionsPolynomial& Add(const Polynomial&);Polynomial& Sub(const Polynomial&);Polynomial& Mul(const Polynomial&);Polynomial& Div(const Polynomial&);// …
};
1. 15 +x
p1:
p2:
• We don’t need operator overloading.
12 +xp3:
p = p1 + p2 * p3 / p1;
class Polynomial {
public:// operator functionsPolynomial& operator+=(const Polynomial&);Polynomial& operator-=(const Polynomial&);Polynomial& operator*=(const Polynomial&);Polynomial& operator/=(const Polynomial&);// …
};
Polynomial operator+(const Polynomial&, const Polynomial&);Polynomial operator-(const Polynomial&, const Polynomial&);Polynomial operator*(const Polynomial&, const Polynomial&);Polynomial operator/(const Polynomial&, const Polynomial&);
2.
PDF created with pdfFactory Pro trial version www.pdffactory.com
Operator functions: advantagesOperator functions: advantageslWithout overloaded operators
Polynomial f(Polynomial p1, Polynomial p2, Polynomial p3) {return p1.Add((p2.Mul(p3)).Div(p1));
}
Polynomial f(Polynomial p1, Polynomial p2, Polynomial p3) {return p1 + p2 * p3 / p1;
}
lWith overloaded operators
• Polynomial interface communicates with polynomial abstraction.
• Polynomial with overloaded operators are more readable and maintainable.
• Polynomial with overloaded operators are more efficient.
Solution domain terminology
Problem domain terminology
PDF created with pdfFactory Pro trial version www.pdffactory.com
Object-OrientaphiliaEverything is an Object!
Everything should be Object-Oriented.
(Single-rooted) class hierarchy
A clean C++ program tends to be a forest of classes rather than a single large tree.
A lot of things don't fit into class hierarchies.
Built-in data types, complex number, date, time, string, …
1. express concepts directly in codeClasses
2. express relations among concepts directly in codeClass Hierarchy, Parameterization
3. express independent concepts in independent codeMultiple Class Hierarchies, Parameterization
4. compose code representing concepts freely wherever the composition makes senseObject-Oriented Programming, Generic Programming
• C++ high level ideas:
PDF created with pdfFactory Pro trial version www.pdffactory.com
Generic programming: A definitionGeneric programming: A definition
Independent concepts should be independently represented and should be combined only when needed.
• Generic programming is programming with concepts.- Alex Stepanov
• Template- The basis for generic programming in C++.
- Templates provide direct support for generic programming.
Generic Programming: programming using templates to express algorithms and data
structures parameterized by data types, operations, and polices.- Bjarne Stroustrup
Object-Oriented Programming Run-time polymorphismVirtual functions
Generic Programming Compile-time polymorphismTemplates
• Generic programming is more than List<T>.
PDF created with pdfFactory Pro trial version www.pdffactory.com
A motivation example: Range and SwapA motivation example: Range and Swap§ Half-Open range: [low, high)
low highvalue// Range concept (for integers)class Range { // simple value type int value, low, high; // invariant: low <= value < high void check(int v) { if (!(low<=v && v<high)) throw Range_error(); }public: Range(int lo, int v, int hi) : low(lo), value(v), high(hi) { check(v); }
Range& operator=(const Range& a) { check(a.v); value = a.value; return *this; }
Range& operator=(int a) { check(a); value = a; return *this; } operator int() { return value; }};
// Range concept (for doubles)class Range { // simple value typedouble value, low, high; // invariant: low <= value < high
check(double v) { if (!(low<=v && v<high)) throw Range_error(); }public: Range(double lo, double v, double hi) : low(lo), value(v), high(hi)
{ check(v); }Range& operator=(const Range& a) { check(a.v); value =
a.value; return *this; }
Range& operator=(double a) { check(a); value = a; return *this; } operator double() { return value; }};
// Range concept (for points)class Range { // Simple value type Point left, middle, right; // Invariant: left <= middle < right void check(Point p) { if (left > p || p >= right) throw RangeErr(); }public: Range(Point p1, Point p2, Point p3) : left(p1), middle(p2), right(p3)
{ check(middle); } Range& operator=(const Range& r) { check(r.middle); middle = r.middle;
return *this; } Range& operator=(const Point& p) { check(p); middle = p; return *this; } operator Point() const { return middle; }};
PDF created with pdfFactory Pro trial version www.pdffactory.com
Range concept (template version)Range concept (template version)template<class T> class Range { // simple value type T low, value, high; // Invariant: low <= value < high void check(T v) { if !(low <= v && v < high) throw RangeErr(); }public: Range(T lo, T val, T hi) : low(lo), value(val), high(hi) { check(value); } Range& operator=(const Range& r) { check(r.value); value = r.value;
return *this; } Range& operator=(const T v) { check(v); value = v; return *this; } operator T() const { return value; }};
temp
b
template<class T>void Swap(T& a, T& b) // family of swaps{
const T temp = a; // copy ctora = b; // assignment operatorb = temp;
}
a
PDF created with pdfFactory Pro trial version www.pdffactory.com
Template InstantiationTemplate Instantiationvoid f(){
Range r; // error: Range is not a typeRange<int> ri(0, 1, 2); // ok: Range<int> is a typeRange<double> rd(0, 2.7182, 3.1416); // ok: another typeRange<Point> rp(Point(), Point(1, 2), Point(-1,2)); // ok: yet another typeRange<complex<double> > rc(complex<double>(0, 0), complex<double>(1, 1),
complex<double>(2, 2)); // errorint a = 2, b = 3; Point p1(1, 0), p2(2, 0);Swap(a, b); Swap(p1, p2);
}
Class Template
(Template) Class
Object
Instantiation
Construction
Object-Oriented programming
Function Template
(Template) Function
Instantiation
Function call
CallProcedural
programming
Generic programming
PDF created with pdfFactory Pro trial version www.pdffactory.com
SingleSingle--rooted based containersrooted based containers
• Intrusive container: an object need have a special base class or link field to be a member of a container.
Narrow interface
Fat interface
Vector
ListMap
Object
Container
VectorList
Map
• C++ doesn’t have a universal class Object.- No semantics - Sloppy interfaces
PDF created with pdfFactory Pro trial version www.pdffactory.com
CC++++ standard library organizationstandard library organization
Standard C++ = C++ programming language (core language) + standard library
Containers
Algorithms
~ 12 containers
~ 60 algorithms
find find_if for_each
copy countsort transform
unique fill generateremove reverserandom_shuffle
binary_search set_union…
vector setmap listmultimap
multiset bitsetstack queue
deque valarraystring bitsetContainer
Algorithm
Iterator
Iterator
Class templates
Function templates
PDF created with pdfFactory Pro trial version www.pdffactory.com
ContainersContainers• A container is an object that holds other objects.
......
begin end
rep …map:
Node
Nodekey, value
(pair)
• A pair of iterators define a sequence:– The beginning– The end (one-beyond-the-last element) à Half-open range
• The standard containers are logically interchangeable.
vector:rep …
list:rep …
set, multimap, multiset
stack, queue, deque, priority_queue
• Sequence: string, array, vector, tree, I/O stream, file, (doubly-linked) list, stack, queue, set, (various) hash tables, singly-linked list, …
PDF created with pdfFactory Pro trial version www.pdffactory.com
Containers: InterfacesContainers: Interfacestemplate<class T> class std::vector {// ctors, assignment op., dtors// …iterator begin();iterator end();size_type size();bool empty();T front();T back();void push_back(const T& t);void pop_back();T operator[](int index);void resize(size_type sz, T val = T());// other member functions
};
template<class T> class std::list {// ctors, assignment op., dtors// …iterator begin();iterator end();size_type size();bool empty();T front();T back();void push_back(const T& t);void pop_back();void push_front(const T& t);void pop_front();T splice (iterator pos, list& x);// other member functions
};
template<class Key, class T> class std::map {// ctors, assignment op., dtors// …iterator begin();iterator end();size_type size();bool empty();void push_back(const T& t);void pop_back();T front();T back();T operator[](Key& k);iterator lower_bound(const key& k);iterator upper_bound(const key& k);// other member functions
};
PDF created with pdfFactory Pro trial version www.pdffactory.com
Iterators: IntroductionIterators: Introduction
l Iterators are generalization of pointers. They are objects that point to other objects.
=*p -> ==!= ++ *p=
--+ - += -=
< <= > >=[ ]
Pointer arithmetic operations
• Each kind of container provides its own iterators that support a standard set of iterator operations.
Input Iterator Output Iterator
Forward Iterator
Bidirectional Iterator
Random Access Iterator
l Iterators are the glue that holds containers and algorithms together.
Iterator categories
PDF created with pdfFactory Pro trial version www.pdffactory.com
Iterator categoriesIterator categories
...
• Input iterator: read-only
template<class InputIter, class T>InputIter find(InputIter first, InputIter last, const T& v){
for (; first != last && *first != v; first++) ;return first;
}
vector<int> v; v.push_back(2); v.push_back(3); v.push_back(10);vector<int>::iterator it = find(v.begin(), v.end(), 10);std::string a = “Make as simple as possible, but no simpler.”;string::iterator it2 = find(a.begin(), a.end(), ‘k’);int a[10];int* p = find(a, a + 10, ‘0’);
- find
- count
- equal
Input Iterator Output Iterator
Forward Iterator
Bidirectional Iterator
Random Access Iterator
PDF created with pdfFactory Pro trial version www.pdffactory.com
...
• Bidirectional iterator
...
• Forward iterator: Read and Write
...
• Output iterator: write-only
- copy
Iterator categories Iterator categories cont.cont.
- replace
- reverse_copy
- listPDF created with pdfFactory Pro trial version www.pdffactory.com
...
• Random access iterator
- sort
- vector
Iterator categories Iterator categories cont.cont.
ProgramsPrograms• Counting, Comparison, Copy/Replace, Finding, Sorting, Searching, set
operations, Merge/Splice, String manipulation, Array operations, Permutations and more …
// first “real program”vector<int> v;for (int i = 0; i < 100; ++i)
v.push_back(i * i);
1.
int Sum = accumulate(V.begin(), V.end(), 0); 3.
template<class In, class T>T accumulate(In first, In last, T init);
2.
PDF created with pdfFactory Pro trial version www.pdffactory.com
Programs Programs ……
#include <string> #include <vector> #include <iostream> #include <algorithm>using namespace std; int main() {
vector<string> v; string s; while (cin>>s) v.push_back(s); // read a file of wordssort(v.begin(),v.end()); // sort the words ostream_iterator<string> os(cout,"\n"); unique_copy(v.begin(),v.end(),os); // output unique words
}
7..
template<class In, class T>T binary_search(In first, In last, const T& val);
4.
bool b = binary_search(V.begin(), V.end() – 5, 1600);5.
random_shuffle(V.begin(), V.end());vector<int>::iterator it = find(V.begin(), V.end(), 2401);// …
6.
PDF created with pdfFactory Pro trial version www.pdffactory.com
CC++++ standardization processstandardization process
• ~ 1990: Formal C++ standardization start• 1997-1998: First C++ standard document à C++98• 2001-2009: Second C++ standard à C++0X
• WG21: Working Group for C++
- Core Language- Library- Performance- Evolution
http://www.open-std.org/jtc1/sc22/wg21
C++0X is almost %100 compatible with C++98.
• ISO/IEC JTC1/SC22/WG21 C++ Standards Committee
• Major design criteria: Prefer introduction of new features through the standard library, rather than extending the core language.
PDF created with pdfFactory Pro trial version www.pdffactory.com
CC++++0X: Language0X: Language
range-based for loop
Generalized constant expressions
Move semantics
Variadic templates
Strongly typed enumerations
Lambda functions
Concepts
Unicode string literals
Initializer lists
Null pointer
Delegating and Inheriting constructors
long long built in type
PDF created with pdfFactory Pro trial version www.pdffactory.com
CC++++0X: Library0X: Library
Random number generators
Hash tables
Regular expressions
Tuples
Smart pointers
Thread and multithreaded programming
Facilities for template meta-programming
PDF created with pdfFactory Pro trial version www.pdffactory.com
Some notes, suggestions and Some notes, suggestions and recommendationsrecommendations
• You don’t have to know every detail of C++ to write good programs.
l Focus on programming techniques, not on language features.
l The only way to learn a new programming language is by writing programs in it.
- Brian Kernighan & Dennis Ritchie
l Programming is part practical, part theory.
l Programming is understanding. - Kristen Nygaard
• No programming language is perfect.
• A programming language is really a very tiny part of the world. Software engineering is far more than just programming language.
• Look at C++ as a new language.
• A programming language isn’t just a bunch of features.
PDF created with pdfFactory Pro trial version www.pdffactory.com
References
§§ Andrew Koenig and Barbara MooAndrew Koenig and Barbara Moo. . Accelerated CAccelerated C++++: Practical Programming by : Practical Programming by Example.Example. AddisonAddison--Wesley, 2000.Wesley, 2000.
§§ Brian Kernighan and Dennis M. Ritchie. Brian Kernighan and Dennis M. Ritchie. The C Programming Language.The C Programming Language. PrenticePrentice--Hall, Englewood Cliffs, New Jersey. 1988. 2Hall, Englewood Cliffs, New Jersey. 1988. 2ndnd edition. edition.
§§ Matthew H. Austen. Matthew H. Austen. Generic Programming and the STLGeneric Programming and the STL-- Using and Extending the Using and Extending the CC++++ Standard Template LibraryStandard Template Library, Addison, Addison--Wesley, Reading, MA, 1999. Wesley, Reading, MA, 1999.
§§ GGrady Booch, Robert A. Maksimchuk, Michael W. Engle, Bobbi J. Yourady Booch, Robert A. Maksimchuk, Michael W. Engle, Bobbi J. Young, Jim ng, Jim Conallen and Kelli A. Houston. Conallen and Kelli A. Houston. ObjectObject--Oriented Analysis and Design with Oriented Analysis and Design with ApplicationsApplications, , Benjamin/Cummings, Redwood City, CA, 2007. 3Benjamin/Cummings, Redwood City, CA, 2007. 3rdrd edition. edition.
§§ Bjarne Stroustrup. Bjarne Stroustrup. The CThe C++++ Programming Language. Programming Language. AddisonAddison--Wesley, Reading, MA, Wesley, Reading, MA, 2000. special edition. 2000. special edition.
§§ Bjarne Stroustrup. Bjarne Stroustrup. The Design and Evolution of CThe Design and Evolution of C++++, , AddisonAddison--Wesley, Reading, MA, Wesley, Reading, MA, 1994. 1994.
§§ Eric Gamma et alEric Gamma et al. . Design Patterns: Elements of Reusable ObjectDesign Patterns: Elements of Reusable Object--Oriented SoftwareOriented Software. . AddisonAddison--Wesley, 1995.Wesley, 1995.
§§ Bjarne Stroustrup: Bjarne Stroustrup: Programming Programming ---- Principles and Practice Using C++.Principles and Practice Using C++. AddisonAddison--Wesley,Wesley, December 2008.December 2008.
PDF created with pdfFactory Pro trial version www.pdffactory.com
The EndThe End
Thank you for your patience (!)Thank you for your patience (!)
&&
AAPDF created with pdfFactory Pro trial version www.pdffactory.com
Top Related