advanced c programming
Download
Skip this Video
Download Presentation
Advanced C++ Programming

Loading in 2 Seconds...

play fullscreen
1 / 69

Advanced C++ Programming - PowerPoint PPT Presentation


  • 150 Views
  • Uploaded on

Advanced C++ Programming. Guillaume Caumon, September 2007. 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, .

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Advanced C++ Programming' - paniz


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
advanced c programming

Advanced C++ Programming

Guillaume Caumon, September 2007

introduction
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
Maintenance:
  • Bug fixes
  • User requests
  • Backward compatibility

Conception

Development

Testing

Release

Software development

Energy = Cost

Time

introduction4
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
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
Outline
  • Some Programming Rules
  • Optimizing C++ programs
  • Generic Programming
  • A short STL overview
  • Some Design Patterns
resolving ambiguities namespace
Resolving ambiguities: namespace

ANSI feature

namespace Gocad1 {

class MainWindow{ … };

}

namespace Gocad2 {

class MainWindow{ … };

}

using namespace Gocad1;

using Gocad2::MainWindow;

Gocad1::MainWindow window(…);

reference s or pointers
References or pointers ?

Goal: refer to objects

References are as cheap as pointers,

and more convenient

  • Rules:
    • In function parameters, use
    • const T& varinstead ofT var
    • A nil reference does not exist, so use pointers whenever you would need ‘nil references’.
    • pointers can be reassigned, references can’t.
exercise
#include

class Traced {

public:

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 flags );

execute_p( vector* flags );

execute_ref( vector& flags );

execute_cref( const vector& flags );

};

Exercise

traced.h

exercise11
Exercise

traced.cpp

int main( int argc, char** argv ) {

cout << "Creating the vector of data" << endl;

vector 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;

}

g++ -o Traced traced.cpp

./Traced

exceptions
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”

}

constructor and assignment
class String {

public:

String( const char* value );

String( const String& rhs );

~String();

String& operator=( const String& rhs);

private:

char* data_;

};

file.h

Constructor and assignment

int main() {

String s1 = “tutu”;

String s2( “toto” );

s2 = s1;

};

implicit type conversions
Implicit type conversions

class Rational {

Rational( int num, int denom = 1 );

double operator double() const;

};

void print_rational(

ostream& out, const Rational& fraction

) {

out << fraction->num() << “ / ” << fraction->denom() << endl;

}

int main( int argc, char** argv ) {

Rational r(1,2);

double d = .5 * r;

print_rational( cout, d );

return 1;

}

avoiding implicit conversions
Avoiding implicit conversions

class Rational {

explicit Rational(

int num,

int denom = 1

);

operator double() const;

};

ANSI feature

overloading operators i
Overloading operators (I)

class Rational {

Rational& operator =( const Rational& rhs );

bool operator ==( const Rational& rhs );

Rational operator +( const Rational& rhs );

Rational& operator +=( const Rational& lhs );

Rational& operator++(); // ++a (prefix)

Rational operator++(int); // a++ (postfix)

};

overloading operators ii
Overloading operators (II)

class Rational {

// …

Rational operator+( int rhs );

friend Rational operator+(

int lhs, const Rational& rhs

);

};

Rational operator+(

int lhs, const Rational& rhs

) { //… }

If the left-hand side of the expression is of a different type, the operator MUST be a non-member

modifying non const member in const member
Modifying non const member in const member

Downgrade the const member

Non ANSI: use const cast

ANSI: use the mutable keyword

i c main programming rules

I- C++ main programming rules

Miscellaneous

Object design

what is oop
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
the interface in c
The interface in C++

Usually defined in a header (.h) file:

class Car {

public:

// Members can be accessed from any object

protected:

// Can only be accessed by Car and its derived objects

private:

// Can only be accessed by Car for its own use.

};

aggregation or composition
Aggregation or Composition?

4

Person

Brain

Car

Wheel

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.

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, etc.

classes basic design rules
Classes: Basic Design Rules

Hide all member variables

Hide implementation functions and data

Minimize the number of public member functions

Avoid default constructors

Avoid overloading (can be ambiguous)

Use const members whenever possible / needed

Be aware of compiler generated functions

inheritance quick review
GeomShape

class GeomShape {

//…

};

class Circle : public GeomShape {

//…

};

file.h

Circle

Inheritance: quick review

“A circle is a shape”

public inheritance philosophy
Public Inheritance Philosophy

Public inheritance ‘is a’

In other words:

What is applies to a base class applies to its derived classes

Three aspects to consider:

class public interface

class relationship with derived classes

class internal cookware

polymorphism
Employee

Boss

Polymorphism

Mechanism that allows a derived class to modify the behavior of a member declared in a base class

class Employee {

public :

virtualfloat income(); // 1000

};

class Boss : public Employee {

public :

virtual float income(); // 10000

};

polymorphism27
Employee

Boss

Polymorphism

A pure virtual function just defines the interface, and leaves the implementation to derived classes

class Employee {

public :

virtualfloat income() = 0;

// not implemented

};

class Boss : public Employee {

public :

virtual float income(); // implemented

};

private inheritance philosophy
Private Inheritance Philosophy

Private inheritance is implemented in term of

This is an equivalent variant of agregation:

class Car : private engine {

//…

};

class Car {

private:

Engine engine_;

};

inheritance and fonctions
Inheritance and fonctions

can

have...

No

No

public

public

Yes

(must)

public

virtual

Yes/no

public

Yes

(must)

public

virtual

Yes / no

protected

Yes

(must)

public

virtual

No

public

polymorphism mechanism
Base::vf1

Base

Base::vf2

vtbl_

Base::vf3

Derived

Derived::vf1

Base

Derived::vf3

vtbl_

Polymorphism Mechanism
consequences
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
Cast operators

Avoid c-style casting operators.

ANSI C++ provides 4 cast operators :

Type* static_cast(expression)

Type* const_cast(expression)

Type* dynamic_cast(expression)

Type* reinterpret_cast(expression)

additional guidelines
Additional guidelines...

Avoid multiple inheritance: use composition

Forbid default parameters in virtual functions

Don’t redefine (overload) a non virtual function

Differentiate between layering and inheritance

optimization
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
Lazy evaluation

Compute only when needed

Examples:

Matrix operator +

Gocad association mechanism

anticipated evaluation
Anticipated evaluation

Compute once, and cache information.

Examples:

Statistics manager

Dynamic arrays

return value optimization
Return value optimization

A first try...

class Complex {

//

};

const Complex operator*(

const Complex& a, const Complex b

) {

Complex c;

c.set_real( a.real() * b.real() );

c.set_im( a.im() + b.im() );

return c;

}

return value optimization40
Return value optimization

A second try...

class Complex {

//

};

const Complex& operator*(

const Complex& a, const Complex b

) {

Complex c;

c.set_real( a.real() * b.real() );

c.set_im( a.im() + b.im() );

return c;

}

return value optimization41
Return value optimization

A last try...

class Complex {

//

};

const Complex operator*(

const Complex& a, const Complex b

) {

return Complex(

a.real() * b.real(),

a.im() + b.im()

);

}

...But don’t alter your code quality for that !!

some rules
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

example dynamic arrays
Example: dynamic arrays

Goal: add items dynamically to a set.

Problem:

- dynamic memory allocation is time-consuming

- the number of elements is not known from the start

Proposal:

Allocate N elements, then add items

Allocate 2N elements, then copy existing items, then add items

Allocate 4N elements, then copy existing items, then add items

parameterize classes
template class List {

public :

List( int nb_items );

~List();

void append_item( const T& item );

void remove_item( const T& item );

void remove_all();

//…

};

list.h

Parameterize classes…

Case of most container classes: store data of arbitrary types.

or fonctions
/**

* Swaps two objects of type T.

* T should provide copy constructor

* and operator=

*/

template void swap(

T& t1, T& t2

);

swap.h

template void swap(

T& t1, T& t2

) {

T tmp(t1);

t1 = t2;

t2 = tmp;

}

swap.h

… or fonctions
templates
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 List {

//…

};

/**

* Sorts a List of objects of type T.

* T must provide order operators <

*/

template class ListSorter {

public :

ListSorter( List& list );

void sort();

private :

List& list_;

};

list.h

Example
functors
Functors

Goal: replace pointers to functions

How ?

[return type]operator()( [type param] );

Type checking

Supports inline functions

Example:

Generator

Unary Function

Binary function

Predicates

generic programming
Generic Programming

Idea:

Replace virtual functions by mandatory functions of template arguments…

Example: the GSTL[N. Rémy – A. Shtuka – B. Lévy – J. Caers]

example matrix objects 1
Example: Matrix objects (1)

class Matrix {

public:

virtual double operator()( int i, int j ) = 0;

};

class SymmetricMatrix : public Matrix {

Public:

virtual double operator()( int i, int j );

};

class UpperTriangularMatrix : public Matrix {

public:

virtual double operator()( int i, int j );

};

Any problem?

static polymorphism
Static Polymorphism
  • Replace virtual function by a template parameter
  • Delegate the function to the template argument
example matrix objects 2
Example: Matrix objects (2)

class SymmetricStorage {

public:

double operator()( int i, int j );

};

class UpperTriangularMatrix {

//…

};

template class Matrix {

public:

double operator()( int i, int j ) {

return storage_(i, j);

}

private:

STORAGE storage_;

};

example matrix objects 254
Example: Matrix objects (2)

template class Matrix {

public:

//…

bool is_invertible();

bool is_sparse();

bool is_symmetric_positive_definite();

//…

};

  • Delegation to STORAGE:
  • Burdens the STORAGE concept
  • May end up with inconsistencies
example matrix objects 3
Example: Matrix objects (3)

template class Matrix {

public:

LEAF& leaf() {

return static_cast( *this );

}

};

class SymmetricMatrix:

public Matrix {

//…

};

Derived type is known at compile-time

Derived classes can define their own functions

template specialization
Template Specialization
  • Redefine the implementation for some template arguments
application metaprograms
Application: metaprograms

template class Factorial {

public:

enum { value = N * Factorial::value };

};

template <> class Factorial<1> {

public:

enum { value = 1 };

};

Void f() {

const int fact4 = Factorial<4>::value;

}

application metaprograms58
Application: metaprograms

Practical interest:

Specialization for optimizing behavior for small objects

Example :

Expand loops in vector / tensor /matrix calculus

include files
Include files

#include

#include

#include

#include

#include

#include

….

stl containers
STL containers

std::vector vect(30);

vect[2] = 3;

//…

for(

std::vector::iterator it(vect.begin());

it != vect.end(); it++

) {

int& cur_value = *it;

}

finite state machine
Finite state machine

To solve a linear system of equations…

add equation coefficients one by one, then invert the matrix

Class TransactionBased {

public:

start_task1();

do_action1(…);

end_task1();

start_task2(); // can be started only if task1 was completed

do_action2(…);

end_task2();

private:

enum State{ UNDEF=0, TASK1=2, TASK2 = 4};

};

composite
Composite

Treat a collection of objects as an object itself

Graphic

Text

Line

Picture

singleton
Singleton

Ensure that an object is instantiated only once

Singleton

static Singleton* instance()

observer
Observer

Subject

update()

notify()

ConcreteObserver

Observer

Define a dependency between objects

factory method
Creator

create_product()

ConcreteCreator

ConcreteProduct

Factory method

Create the right type of elements in an abstract framework

Product

conclusions
Conclusions
  • Concrete Applications...
  • Programming project
  • Oral presentation of the use of one particular design pattern in Gocad (Dec 2, 2005)
  • In your master’s projects
references
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, MoreEffective C++, Addisson Wesley.
  • Meyers, Effective STL, Addisson Wesley.
  • http://www.oonumerics.org/blitz/papers/
  • Gautier et al., Cours de Programmation par objets, Masson.
ad