• Keine Ergebnisse gefunden

Object-Oriented Programming for Scientific Computing

N/A
N/A
Protected

Academic year: 2021

Aktie "Object-Oriented Programming for Scientific Computing"

Copied!
29
0
0

Wird geladen.... (Jetzt Volltext ansehen)

Volltext

(1)

Object-Oriented Programming for Scientific Computing

Namespaces and Inheritance

Ole Klein

Interdisciplinary Center for Scientific Computing Heidelberg University

ole.klein@iwr.uni-heidelberg.de

5. Mai 2015

(2)

Namespaces

• Namespaces permit classes, functions and global variables to be grouped under one name. This way, the global namespace can be divided into subareas, each of which has its own name.

• A namespace is defined by:

n a m e s p a c e N a m e {

// classes , f u n c t i o n s etc . b e l o n g i n g to the n a m e s p a c e }

Here theNameis an arbitrary name which complies with the rules for variable and function names.

• In order to use a construct from a namespace, the name of the namespace followed by two colons must be written before the name of the construct, e.g.std::max(a,b).

• Each class defines its own namespace.

(3)

Namespaces

Namespaces

• With the keywordusingone or all of the names from another namespace are made available to the current namespace. An example that is often used is the line

u s i n g n a m e s p a c e std ;

After this line, all constructs from the namespacestdcan be used without a prefix, e.g.max(a,b). This must not lead to ambiguity.

• If only one name (or a small number of names) should be imported, it can be specified explicitly, e.g.using std::cout;

• The keywordusingshould be used sparingly.

• Namespaces may also be nested as a hierarchy.

(4)

Namespaces: Example

Namespaces are particularly useful when there is a possibility that two classes, global variables or functions with the same name (and for functions same argument list) exist in different parts of the code developed independently from each other. This leads to errors with the error message... redefined. Using namespaces this can be prevented:

// n a m e s p a c e s

# i n c l u d e < i o s t r e a m >

n a m e s p a c e f i r s t {

int var = 5;

}

n a m e s p a c e s e c o n d {

d o u b l e var = 3 . 1 4 1 6 ; }

int m a i n () {

std :: c o u t < < f i r s t :: var < < e n d l ; std :: c o u t < < s e c o n d :: var < < e n d l ; r e t u r n 0;

}

(5)

Nested Classes

Nested Classes

• Often a class needs other “auxiliary classes”.

• Those may be specific to the implementation and shouldn’t be visible from the outside.

• Example:

List elements

Iterators

Exceptions (Objects for error messages, next lecture)

• One can realise those as classes within the class (so-called nested classes).

• Advantages:

The global namespace is not “polluted”.

Affiliation with the other class is emphasized.

(6)

Nested Classes: Example

c l a s s O u t e r {

p u b l i c: ...

c l a s s I n n e r 1 {

...

};

p r i v a t e: ...

c l a s s I n n e r 2 {

v o i d foo () ; };

};

v o i d O u t e r :: I n n e r 2 :: foo () {

...

}

(7)

Nested Classes

Example: Implementation of a Set using a List

c l a s s Set {

p u b l i c:

Set () ; // e m p t y set

~ Set () ; // d e l e t e the set

v o i d I n s e r t (d o u b l e) ; // i n s e r t ( o n l y o n c e ) v o i d D e l e t e (d o u b l e) ; // d e l e t e ( if in set ) b o o l C o n t a i n s (d o u b l e) ; // t r u e if c o n t a i n e d in set p r i v a t e:

s t r u c t S e t E l e m {

d o u b l e i t e m ; S e t E l e m * n e x t ; };

S e t E l e m * f i r s t ; };

SetElemcan only be used in theSet, therefore all its attributes can bepublic

(Remember:struct isclasswithpublic as default).

(8)

Inheritance

• Classes allow the definition of components that represent certain concepts of the real world or the program.

• The relationship between the various classes can be expressed through inheritance. e.g. the classesCircleandTrianglehave in common that they represent a geometric shape. This should also be reflected in the program.

• In C++ it is possible to write:

c l a s s S h a p e { . . . } ;

c l a s s C i r c l e : p u b l i c S h a p e { . . . } ; c l a s s T r i a n g l e : p u b l i c S h a p e { . . . } ;

The classesCircleandTriangleare derived fromShape, they inherit the properties ofShape.

• It is thus possible to summarize common characteristics and behaviors of

CircleandTrianglein Shape. This is a new level of abstraction.

(9)

Inheritance

Inheritance

• A derived class is an

extension of the base class. It has all the properties of the base class and adds some more.

specialization of the base class. As a rule, it represents a particular realization of the general concept.

• The interplay of expansion and restriction is the source of the flexibility (but also sometimes the complexity) of this technique.

(10)

Protected Members

• Next toprivateandpublicclass members, there is a third category:protected

• It is not possible to accessprotectedmethods and attributes from the ouside, only from the class itself, as withprivate

• However,protectedmethods and attributes stayprotectedwhen using public

inheritance, this means they can also be accessed by all derived classes.

• There is the widespread opinion thatprotectedisn’t needed and that the use of this type is an indication of design errors (such as missing access

functions. . .).

(11)

Inheritance

Protected Members: Example

c l a s s A {

p r o t e c t e d: int c ; v o i d f () ; };

c l a s s B : p u b l i c A {

p u b l i c: v o i d g () ; };

B :: g () {

int d = c ; // a l l o w e d f () ; // a l l o w e d }

int m a i n () {

A a ; B b ;

a . f () ; // not a l l o w e d b . f () ; // not a l l o w e d }

(12)

Protected Constructors

With the help ofprotectedone can prevent the creation of objects of the base class:

c l a s s B {

p r o t e c t e d: B () ; };

c l a s s D : p u b l i c B {

p u b l i c:

D () ; // c a l l s B () };

int m a i n () {

B b ; // not a l l o w e d D d ; // a l l o w e d }

(13)

Inheritance Class Relations and Inheritance Types

Class Relations

Is-a ClassY has the same functionality (maybe in specialised form) as classX.

Object y(of classY) can be used as anx(of classX).

Example: a VW Beetle is a car

Has-a (aggregation): Class Zconsists of subobjects of typeXandY.

z has anx and ay.

Example: a car has a motor, doors, tires,. . .

Knows-a (assoziation): ClassYhas a reference (or pointer) to objects of class

X.

x knows ay, uses ay.

Example: A car is registered to a person (the person possesses it, but isn’t made of it, it isn’t a part of her or him).

One can implement has-a (in possession of) using knows-a.

(14)

Public Inheritance

c l a s s X {

p u b l i c: v o i d a () ; };

c l a s s Y : p u b l i c X {

p u b l i c: v o i d b () ; };

• Allpublicmembers ofXarepublicmembers ofY

• The implementation is inherited, i.e.

Y y ;

y . a () ; // c a l l s m e t h o d a of X

(15)

Inheritance Class Relations and Inheritance Types

Public Inheritance

• Is-a-relation

X X

Y

• Objects of the derived class can be used as objects of the base class, but then only the base class part of the object is accessible.

(16)

Slicing

c l a s s X {

p u b l i c: v o i d a () ; };

c l a s s Y : p u b l i c X {

p u b l i c: v o i d b () ; };

int m a i n () {

Y y ;

y . a () ; // c a l l s m e t h o d a of the X p a r t of y X & x = y ;

x . a () ; // c a l l s m e t h o d a of the X p a r t of y

x . b () ; // not allowed , o n l y m e t h o d s of X a c c e s s i b l e }

If an object of the derived classe is passed call-by-value instead of an object of the base class, then only the base class part is copied.

(17)

Inheritance Class Relations and Inheritance Types

Private Inheritance

c l a s s X {

p u b l i c: v o i d a () ; };

c l a s s Y : p r i v a t e X {

p u b l i c:

v o i d b () ; };

• Allpublicmembers ofXareprivatemembers ofY

• The has-a relation is in principle equivalent to :

c l a s s Y {

p u b l i c:

v o i d b () ; p r i v a t e:

X x ; // a g g r e g a t i o n }

Therefore, private inheritance is not particularly essential.

• It is used to implement a class by means of another.

(18)

Protected Inheritance

c l a s s X {

p u b l i c: v o i d a () ; };

c l a s s Y : p r o t e c t e d X {

p u b l i c: v o i d b () ; };

• Allpublicmembers ofXareprotectedmembers ofY

• Is actually never needed.

(19)

Inheritance Class Relations and Inheritance Types

Overview: Access Control in Inheritance

Access Rights Inheritance Type

in the Base Class public protected private

public public protected private

protected protected protected private

private – – –

(20)

Access to Methods and Attributes of the Base Class

• If there is a variable or method in the derived class with the same name as in the base class (including argument list in the case of methods), then it hides the corresponding variable or method in the base class.

• Access is still possible using the name of the base class as a prefix namespace identifier, as long as this is permitted by the access rights.

(21)

Inheritance Multiple Inheritance

Multiple Inheritance

• A class can be derived from more than one base class.

• If there are any methods or variables with the same name in two or more base classes, then they must be identified by the namespace of the relevant class.

• The constructors of the base classes are called in the order of derivation.

• Should only be used in exceptional cases. Often this can also be solved using a has-a relation (i.e. via an appropriate attribute).

(22)

Multiple Inheritance

# include< i o s t r e a m >

c l a s s T r a c t i o n E n g i n e {

p u b l i c:

f l o a t W e i g h t () {

r e t u r n w e i g h t _ ; };

T r a c t i o n E n g i n e (f l o a t w e i g h t ) : w e i g h t _ ( w e i g h t ) {

std :: c o u t < < " T r a c t i o n E n g i n e i n i t i a l i z e d " < < std :: e n d l ; };

p r o t e c t e d: f l o a t w e i g h t _ ; };

(23)

Inheritance Multiple Inheritance

Multiple Inheritance

c l a s s T r a i l e r {

p u b l i c:

f l o a t W e i g h t () {

r e t u r n w e i g h t _ ; };

T r a i l e r (f l o a t w e i g h t ) : w e i g h t _ ( w e i g h t ) {

std :: c o u t < < " T r a i l e r i n i t i a l i z e d " < < std :: e n d l ; };

p r o t e c t e d: f l o a t w e i g h t _ ; };

(24)

Multiple Inheritance

c l a s s T r a i l e r T r u c k : p u b l i c T r a c t i o n E n g i n e , p u b l i c T r a i l e r {

p u b l i c:

f l o a t W e i g h t () {

r e t u r n T r a c t i o n E n g i n e :: w e i g h t _ + T r a i l e r :: w e i g h t _ ; }

T r a i l e r T r u c k (f l o a t wEngine , f l o a t w T r a i l e r ) : T r a i l e r ( w T r a i l e r ) ,

T r a c t i o n E n g i n e ( w E n g i n e ) {

std :: c o u t < < " T r a i l e r T r u c k i n i t i a l i z e d " < < std :: e n d l ; };

};

(25)

Inheritance Multiple Inheritance

Multiple Inheritance

int m a i n () {

T r a i l e r T r u c k m i k e s T r u c k ( 1 0 . 0 , 2 5 . 0 ) ;

std :: c o u t < < " W e i g h t t r a i l e r t r u c k : " < < m i k e s T r u c k . W e i g h t ()

< < std :: e n d l ;

std :: c o u t < < " W e i g h t t r a c t i o n e n g i n e : " < <

m i k e s T r u c k . T r a c t i o n E n g i n e :: W e i g h t () < < std :: e n d l ; std :: c o u t < < " W e i g h t t r a i l e r : " < <

m i k e s T r u c k . T r a i l e r :: W e i g h t () < < std :: e n d l ; }

Output:

T r a c t i o n E n g i n e i n i t i a l i z e d T r a i l e r i n i t i a l i z e d

T r a i l e r T r u c k i n i t i a l i z e d W e i g h t t r a i l e r t r u c k : 35 W e i g h t t r a c t i o n e n g i n e : 10 W e i g h t t r a i l e r : 25

(26)

C++11: Final

c l a s s X f i n a l {

p u b l i c: v o i d a () ; };

c l a s s Y : p u b l i c X // c o m p i l e r e r r o r {

p u b l i c: v o i d b () ; };

In C++11 it is allowed to mark a class asfinal. Then, further derivation from this class is no longer allowed.

(27)

Inheritance Pros and Cons of Inheritance

Benefits of Inheritance

Software reuse Common features do not have to be written again every time.

Saves time and improves security and reliability.

Code sharing Code in the base class is not duplicated in the derived class. Errors must only be corrected once.

Information hiding The class can be changed without knowing the implementation details.

Closed source extension Is also possible with classes that are only distributed as binary code and a header with declarations.

(28)

Drawbacks of Inheritance

Runtime speed Calling all constructors and destructors when creating and destroying an object, possibly a higher memory consumption when a derived class does not use all the features of the base class.

Program size When using general libraries unnecessary code may be written.

Program complexity High program complexity can be caused by excessive class hierarchies or multiple inheritance.

(29)

Inheritance Pros and Cons of Inheritance

Summary

• Namespaces allow the separation of programs and libraries into logical parts and avoid name clashes

• Nested classes are a good way to hide classes that are only needed within one other class

• Inheritance makes code reuse and the expression of hierarchies possible

protectedandprivateinheritance are rarely needed / used

• Objects of derived classes can be used as objects of their base class, this may lead to slicing

• Inheritance may make coding faster and easier, but may also reduce the efficiency of the resulting code

Referenzen

ÄHNLICHE DOKUMENTE

insert(p, t) Inserts the element t in front of the one the iterator p points to, and returns an iterator that points to the inserted element.. insert(p, i, j) As above, but for

replace_copy(b,e,out,v,v2) Create copy of all elements in range [b:e) re- placing elements which are equal to v with v2 , return iterator to end of copy.

• Traits can be used to specify types and values that depend on one or more template parameters. • Policies can be used to specify parts of algorithms as

Since the units are only used as a template parameter, this only affects the class type but does not require memory... Example: Numbers

This header also contains functions that provide a thread ID and the functionality to detach threads that afterwards run as a separate program (fork).. Mutual Exclusion The header

and no exercise group, because things are still being set up, but you are welcome to attend if you have questions about the lecture or exercises or something else to discuss.. E

~List (); // clean up the list and all nodes Node* first() const; // return a pointer to the first entry Node* next( const Node* n) const; // return a pointer to the node after n

Please modify your implementation again to obtain a doubly linked list: each element should also point to its predecessor.. What is