Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Introduction
C++ supports a variety of programming styles:
procedural (as FORTRAN, pascal, C, ) object-oriented (as Eifel, JAVA, ) generic Features interact with each other. C++ is very flexible, but also very confusing...
Software development
Energy = Cost
Maintenance: - Bug fixes - User requests - Backward compatibility Conception Development Testing
Release
Time
Introduction
The goal of this course is to provide some keys to choose the design which: eases the maintenance process; optimizes performance; optimizes memory requirements.
Prerequisites
A working knowledge of C++ and of the basic object-oriented concepts. What is a pointer ? What is a class ? What is inheritance ?
Outline
Some Programming Rules Optimizing C++ programs Generic Programming A short STL overview Some Design Patterns
References or pointers ?
Goal: refer to objects References are as cheap as pointers, and more convenient Rules: In function parameters, use const T& var instead of T var A nil reference does not exist, so use pointers whenever you would need nil references. pointers can be reassigned, references cant.
#include <vector>
class Traced { public: traced.h Traced(); Traced( int parameter ); Traced( const Traced& rhs ); ~Traced(); Traced& operator=( const Traced& rhs ); private: int impl_; }; Using std::vector; Class Dummy { execute_val( vector<Traced> flags ); execute_p( vector<Traced>* flags ); execute_ref( vector<Traced>& flags ); execute_cref( const vector<Traced>& flags ); };
Exercise
Exercise
traced.cpp int main( int argc, char** argv ) { cout << "Creating the vector of data" << endl; vector<Traced> data(2); data[0] = Traced(0); data[1] = Traced(1); cout << "---------------------------\n" << endl; Dummy dummy; dummy.execute_val( data ); dummy.execute_ptr( &data ); dummy.execute_ref( data ); dummy.execute_cref( data ); return 1; }
Exceptions
Goals : improve program safety How ? Framework to bypass the function call stack try { // some code that might cause pbs } throw message catch ( message ) { // special processing Doctor Watson }
ANSI feature
If the left-hand side of the expression is of a different type, the operator MUST be a non-member
What is OOP?
Object-Oriented Programming is a philosophy where the source code of a program is split into reusable objects. What is an object, then? An object is made of two parts: - The interface = catalog of the object features -The implementation = internal machinery
Aggregation or Composition?
Car
4
Wheel
Person
Brain
Aggregation is a relationship in which one object is a part of another. A aggregates B = B is part of A, but their lifetimes may be different Ex: cars and wheels, engine, c etc.
Composition is a relationship in which one object is an integral part of another A composes B = B is part of A, and their lifetimes are the same Ex: person and brain, lung, etc.
Polymorphism
Mechanism that allows a derived class to modify the behavior of a member declared in a base class
Employee Boss
class Employee { public : virtual float income(); // 1000 }; class Boss : public Employee { public : virtual float income(); // 10000 };
Polymorphism
A pure virtual function just defines the interface, and leaves the implementation to derived classes
Employee
class Employee { public : Boss virtual float income() = 0; // not implemented }; class Boss : public Employee { public : virtual float income(); // implemented };
Mandatory
Mandatory
No Yes/no
public public
(must)
Yes
Yes / no
protected
(must)
No
public
Polymorphism Mechanism
Base
vtbl_
Derived Base
vtbl_
Derived::vf1 Derived::vf3
Consequences
Never call a virtual function in a constructor Never declare a virtual function inline Calling a virtual function is more expensive than calling a non-virtual function Be aware of the increased size of classes with virtual functions
Cast operators
Avoid c-style casting operators. ANSI C++ provides 4 cast operators : Type* static_cast<Type>(expression) Type* const_cast<Type>(expression) Type* dynamic_cast<Type>(expression) Type* reinterpret_cast<Type>(expression)
Additional guidelines...
Avoid multiple inheritance: use composition Forbid default parameters in virtual functions Dont redefine (overload) a non virtual function Differentiate between layering and inheritance
Optimization
Main issue: algorithm complexity and memory requirements Main question: which part of the code should be optimized ? 20% of the code is used 80% of the time Code maintenance and debug vs. optimization.
Lazy evaluation
Compute only when needed Examples: Matrix operator + Gocad association mechanism
Anticipated evaluation
Compute once, and cache information. Examples: Statistics manager Dynamic arrays
Some rules...
Overload to avoid implicit type conversions (fine tuning only) Prefer operator += to operator + Prefer generic programming to virtual functions Use inline functions, but not too much... Postpone variable declaration
Parameterize classes
Case of most container classes: store data of arbitrary types.
template<class T> class List { public : List( int nb_items ); ~List(); void void void // }; list.h
or fonctions
/** * Swaps two objects of type T. * T should provide copy constructor * and operator= */
swap.h
template<class T> void swap( T& t1, T& t2 ); template<class T> void swap( T& t1, T& t2 ) { T tmp(t1); t1 = t2; t2 = tmp; } swap.h
Templates
Template code is compiled only when it is used (template instanciation) Keyword class (or typename) or int can be used to qualify template arguments. Members can be required from template arguments
Example
template <class T> class List { // };
/** * Sorts a List of objects of type T. * T must provide order operators < */
list.h
template <class T> class ListSorter { public : ListSorter( List<T>& list ); void sort(); private : List<T>& list_; };
Functors
Goal: replace pointers to functions How ? [return type] operator()( [type Type checking Supports inline functions
Example: Generator Unary Function Binary function Predicates
param]
);
Generic Programming
Idea: Replace virtual functions by mandatory functions of template arguments
Any problem?
Static Polymorphism
Replace virtual function by a template parameter Delegate the function to the template argument
Delegation to STORAGE: - Burdens the STORAGE concept - May end up with inconsistencies
Derived type is known at compile-time Derived classes can define their own functions
Template Specialization
Redefine the implementation for some template arguments
Application: metaprograms
template <int N> class Factorial { public: enum { value = N * Factorial<N-1>::value }; }; template <> class Factorial<1> { public: enum { value = 1 }; }; Void f() { const int fact4 = Factorial<4>::value; }
Application: metaprograms
Practical interest: Specialization for optimizing behavior for small objects Example : Expand loops in vector / tensor /matrix calculus
Include files
#include <iostream> #include <utility> #include <complex> #include <list> #include <vector> #include <map> .
STL containers
std::vector<int> vect(30); vect[2] = 3; // for( std::vector<int>::iterator it(vect.begin()); it != vect.end(); it++ ){ int& cur_value = *it; }
STL algorithms
Ordering Permutations Search and replace
Composite
Treat a collection of objects as an object itself Graphic
Text
Line
Picture
Singleton
Ensure that an object is instantiated only once Singleton
static Singleton* instance()
Observer
Define a dependency between objects Subject
notify()
Observer
update()
ConcreteObserver
Factory method
Create the right type of elements in an abstract framework Creator
create_product()
Product
ConcreteCreator
ConcreteProduct
Conclusions
Concrete Applications... Programming project Oral presentation of the use of one particular design pattern in Gocad (Dec 2, 2005) In your masters projects
References
Brokken et Kubat, C++ Annotations, http://www.icce.rug.nl/docs/cpp.shtml Stroustrup, Le langage C++ (3e ed.), Addisson Wesley, 1996. Gamma et al., Design Patterns, Addisson Wesley, 1995. Meyers, Effective C++, Addisson Wesley. Meyers, More Effective C++, Addisson Wesley. Meyers, Effective STL, Addisson Wesley. http://www.oonumerics.org/blitz/papers/ Gautier et al., Cours de Programmation par objets, Masson.