Sie sind auf Seite 1von 48

From C to C++

A short introduction to C++

Automotive C Programming
July 2000

From C to C++

Automotive C Programming

Date : July 00 Page : 1

Class Concept
Basic concept to package and encapsulated data and code Class types contains :
Class data members, which define the state and attributes of an object of the class type. One or more "constructor" functions, which initialize an object of the class type. One or more "destructor" functions, which perform cleanup functions such as deallocating dynamically allocated memory or closing files. One or more member functions that define the object's behavior

Class types are defined using the class, struct, and union keywords
class and struct are equivalent, except for default access property union differs concerning the allocation

From C to C++

Automotive C Programming

Date : July 00 Page : 2

Class Overview
The class Public part (data and code)

Private part (data and code)

From C to C++

Automotive C Programming

Date : July 00 Page : 3

Class Exemple
Point public : int Get_x (); int Get_y () ; int Norm () ; private : int x ; int y ;

From C to C++

Automotive C Programming

Date : July 00 Page : 4

Access to member
From the class using the name of the members From outside using :: operator (qualified name) Exemples : Point::Get_x () Point::Norm () Point::x (access to private data)

From C to C++

Automotive C Programming

Date : July 00 Page : 5

Class Name and Types


Class declarations introduce new types, called class names, into programs. Using these new class types, you can declare objects (instances) , and the compiler can perform type checking to verify that no operations incompatible with the types are performed on the objects. Examples : class Point{public: unsigned int x; unsigned int y;}; Point pt; // static Point *p_pt = new Point ; // dynamic

From C to C++

Automotive C Programming

Date : July 00 Page : 6

Construction and Destruction


Call to a constructor Void f () { Point pt; // // } Call to the destructor Point *p_pt = new Point; // // delete p_pt ;

From C to C++

Automotive C Programming

Date : July 00 Page : 7

Exhaustive Class Members


Classes can have these kinds of members:
Member functions. Data members. Classes, which include classes, structures, and unions Enumerations Bit fields Type names

From C to C++

Automotive C Programming

Date : July 00 Page : 8

Unions
Unions are class types that can contain only one data element at a time (although the data element can be an array or a class type). The members of a union represent the kinds of data the union can contain. Functions may be members of an union An object of union type requires enough storage to hold the largest member in its member-list

From C to C++

Automotive C Programming

Date : July 00 Page : 9

Bit Fields
Classes and structures can contain members that occupy less storage than an integral type. These members are specified as bit fields. struct Date{ unsigned nWeekDay : 3; // 0..7 (3 bits) unsigned nMonthDay : 6; // 0..31 (6 bits) unsigned nMonth : 5; // 0..12 (5 bits) unsigned nYear : 8; // 0..100 (8 bits) };

From C to C++

Automotive C Programming

Date : July 00 Page : 10

Nested Class Declarations


A class can be declared within the scope of another class. Such a class is called a "nested class." Nested classes are considered to be within the scope of the enclosing class and are available for use within that scope. To refer to a nested class from a scope other than its immediate enclosing scope, you must use a fully qualified name

From C to C++

Automotive C Programming

Date : July 00 Page : 11

Derived class and Inheritance


New classes can be derived from existing classes using a mechanism called inheritance . Classes that are used for derivation are called "base classes" of a particular derived class.

Base class

is a
Derived class

From C to C++

Automotive C Programming

Date : July 00 Page : 12

Inheritance Exemple

ColoredPoint : Point public : SetColor (int red, int green, int blue); public :

Point

int Get_x (); int Get_y () ; int Norm () ; private : int x ; int y ;

private : COLOR color ;

From C to C++

Automotive C Programming

Date : July 00 Page : 13

Multipled Inheritance
A class can be derived from more than one base class. Exemple : class ColoredPoint : Point, Object { ... The order in which base classes are specified is not significant except in certain cases where constructors and destructors are invoked. In these cases, the order in which base classes are specified affects the following:
The order in which initialization by constructor takes place. If your code relies on the Book portion of CollectionOfBook to be initialized before the Collection part, the order of specification is significant. Initialization takes place in the order the classes are specified in the base-list. The order in which destructors are invoked to clean up. Again, if a particular "part" of the class must be present when the other part is being destroyed, the order is significant. Destructors are called in the reverse order of the classes specified in the base-list.

From C to C++

Automotive C Programming

Date : July 00 Page : 14

Static Data Members


Classes can contain static member data and member functions. When a data member is declared as static, only one copy of the data is maintained for all objects (instances) of the class. Static data members are not part of objects of a given class type; they are separate objects. As a result, the declaration of a static data member is not considered a definition. The data member is declared in class scope, but definition is performed at file scope. These static members have external linkage.
class BufferedOutput { public: // Return number of bytes written by any object of this class. short BytesWritten() { return bytecount; } // Reset the counter. static void ResetCount() { bytecount = 0; } // Static member declaration. static long bytecount; }; // Define bytecount in file scope. long BufferedOutput::bytecount;

From C to C++

Automotive C Programming

Date : July 00 Page : 15

Virtual Functions
"Virtual functions" are functions that ensure that the correct function is called for an object, regardless of the expression used to make the function call. Implementation of vurtual functions is based on pointers Example :
Suppose a base class contains a function declared as virtual and a derived class defines the same function. The function from the derived class is invoked for objects of the derived class, even if it is called using a pointer or reference to the base class.

From C to C++

Automotive C Programming

Date : July 00 Page : 16

Abstract Classes
A class that contains at least a virtual function, or whose base class is abstract Abstract classes act as expressions of general concepts from which more specific classes can be derived. You cannot create an object of an abstract class type; however, you can use pointers and references to abstract class types. A virtual function is declared as "pure" by using the purespecifier syntax (=0)

From C to C++

Automotive C Programming

Date : July 00 Page : 17

Controlling Access to Class Members : the protected concept


Class members of a base class can be declared as having private, protected, or public access private
Class members declared as private can be used only by member functions and friends (classes or functions) of the class.

protected
Class members declared as protected can be used by member functions and friends (classes or functions) of the class. Additionally, they can be used by classes derived from the class.

public
Class members declared as public can be used by any function.

From C to C++

Automotive C Programming

Date : July 00 Page : 18

Protected Member Access


Class members declared as protected can be used only by the following:
Member functions of the class that originally declared these members. Friends of the class that originally declared these members. Classes derived with public or protected access from the class that originally declared these members. Direct privately derived classes that also have private access to protected members.

Protected members are not as private as private members, which are accessible only to members of the class in which they are declared, but they are not as public as public members, which are accessible in any function. Protected members that are also declared as static are accessible to any friend or member function of a derived class. Protected members that are not declared as static are accessible to friends and member functions in a derived class only through a pointer to, reference to, or object of the derived class.
From C to C++ Automotive C Programming
Date : July 00 Page : 19

Access Specifiers and Inheritance


3 types of derivation : public, protected and private Rules
A private data in a base class is always private A protected data in a base class is private if you use private derivation, protected in other cases A public data in a base class is private if you use private derivation, protected if you use a protected dervation and public if you use a public derivation

From C to C++

Automotive C Programming

Date : July 00 Page : 20

Friends
In some circumstances, it is more convenient to grant member-level access to functions that are not members of a class or to all functions in a separate class. With the friend keyword, programmers can designate either the specific functions or the classes whose functions can access not only public members but also protected and private members

From C to C++

Automotive C Programming

Date : July 00 Page : 21

Special Member Functions


The special member functions are described briefly in the following list:
Constructors. These functions enable automatic initialization of objects. Destructors. These functions perform cleanup after objects are explicitly or implicitly destroyed. Conversion Functions. These are used to convert between class types and other types. The new operator. This is used to dynamically allocate storage. The delete operator. This is used to release storage allocated using the new operator. The assignment operator (operator=). This operator is used when an assignment takes place.

From C to C++

Automotive C Programming

Date : July 00 Page : 22

Constructors
Constructors are called at the point an object is created. Objects are created as:
Global (file-scoped or externally linked) objects. Local objects, within a function or smaller enclosing block. Dynamic objects, using the new operator. The new operator allocates an object on the program heap or "free store." Temporary objects created by explicitly calling a constructor Temporary objects created implicitly by the compiler Data members of another class. Creating objects of class type, where the class type is composed of other class-type variables, causes each object in the class to be created. Base class subobject of a class. Creating objects of derived class type causes the base class components to be created.

From C to C++

Automotive C Programming

Date : July 00 Page : 23

Destructors
"Destructor" functions are the inverse of constructor functions. They are called when objects are destroyed (deallocated). Designate a function as a class's destructor by preceding the class name with a tilde (~). Example : the destructor for class String is declared: ~String(). The destructor is commonly used to "clean up" when an object is no longer necessary.

From C to C++

Automotive C Programming

Date : July 00 Page : 24

Conversion Functions
Complement to Conversion by constructors Syntax operator <conversion-type-name> () Example : operator int () { ...}

From C to C++

Automotive C Programming

Date : July 00 Page : 25

New Operator
Called when objects are allocated Two syntaxes
simple arrays

Local and global operor :


The global operator new function is called when the new operator is used to allocate objects of built-in types, objects of class type that do not contain user-defined operator new functions, and arrays of any type. When the new operator is used to allocate objects of a class type where an operator new is defined, that class's operator new is called.

From C to C++

Automotive C Programming

Date : July 00 Page : 26

Delete Operator
Memory that is dynamically allocated using the new operator can be freed using the delete operator. The delete operator calls the operator delete function, which frees memory back to the available pool. Using the delete operator also causes the class destructor (if there is one) to be called. There are global and class-scoped operator delete functions. One operator delete function can be defined for a given class; if defined, it hides the global operator delete function. The global operator delete function is always called for arrays of any type. The global operator delete function, if declared, takes a single argument of type void *, which contains a pointer to the object to deallocate. The return type is void (operator delete cannot return a value).

From C to C++

Automotive C Programming

Date : July 00 Page : 27

Assignment Operator
Two operations cause objects to be copied:
Assignment. When one object's value is assigned to another object, the first object is copied to the second object. Therefore: Point a, b; ... a = b; causes the value of b to be copied to a. Initialization. Initialization occurs at the point of declaration of a new object, when arguments are passed to functions by value, and when values are returned from functions by value.

The programmer can define the semantics of "copy" for objects of class type

From C to C++

Automotive C Programming

Date : July 00 Page : 28

Overloading
With the C++ language, you can overload functions and operators. Overloading is the practice of supplying more than one definition for a given function name in the same scope. The compiler is left to pick the appropriate version of the function or operator based on the arguments with which it is called. Example:
double max( double d1, double d2 ) { return ( d1 > d2 ) ? d1 : d2; } int max( int i1, int i2 ) { return ( i1 > i2 ) ? i1 : i2; }

From C to C++

Automotive C Programming

Date : July 00 Page : 29

Matching Mechanism

Function Matching Argument Matching

From C to C++

Automotive C Programming

Date : July 00 Page : 30

Overloading Operators
With C++, you can redefine the function of most built-in operators. These operators can be redefined, or "overloaded," globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be class-member or global functions. The name of an overloaded operator is operator x where x is the operator itself. For example, to overload the addition operator, you define a function called operator+. Similarly, to overload the addition/assignment operator, +=, define a function called operator+=. Although these operators are usually called implicitly by the compiler when they are encountered in code, they can be invoked explicitly the same way as any member or nonmember function is called:
Point pt; pt.operator+( 3 ); 3 to pt. // Call addition operator to add

From C to C++

Automotive C Programming

Date : July 00 Page : 31

Nonredefinable Operators

. .* :: ?: # ##

Member selection Pointer-to-member selection Scope resolution Conditional Preprocessor symbol Preprocessor symbol

From C to C++

Automotive C Programming

Date : July 00 Page : 32

Exceptions
Exceptions occur when a program executes abnormally due to conditions outside the program's control, such as low memory or I/O errors. Abnormal situations should be handled by throwing and catching exceptions. Abnormal situations are not the same as normal error conditions, such as a function executing correctly but returning a result code indicating an error. A normal error condition, for example, would be a file status function indicating a file doesn't exist. For normal error conditions, examine the error code and respond appropriately. Abnormal situations are also not the same as erroneous execution, in which, for example, the caller makes some mistake in passing arguments to a function or calls it in an inappropriate context.
From C to C++ Automotive C Programming
Date : July 00 Page : 33

Exceptions in C++
In C++, the process of raising an exception is called "throwing" an exception. A designated exception handler then "catches" the thrown exception. Syntax: throw (1) // throw an integer exception try { // action } catch (int e) { // catch any integer exception throw (e) ; // example of re routing }
From C to C++ Automotive C Programming
Date : July 00 Page : 34

Template
Templates are mechanisms for generating functions and classes based on type parameters (templates are sometimes called "parameterized types"). By using templates, you can design a single class that operates on data of many types, instead of having to create a separate class for each type. Examples template <class T> T min( T a, T b ) return ( a < b ) ? a : b; template <class T> void MySwap( T& a, T& b ) { T c( a ); Date : July 00 Page : 35 From C to C++ a = b; b =Automotive C Programming c;

Class Template
You can use class templates to create a family of classes that operate on a type. template <class T, int i> class TempClass { public: TempClass( void ); ~TempClass( void ); int MemberSet( T a, int b ); private: T Tarray[i]; int arraysize; };
From C to C++ Automotive C Programming
Date : July 00 Page : 36

Template Instanciation
For a class
template<class T> class X {...}; //Explicit specialization of X with 'int' template<>

class X<int> { };

For a function
The instanciation is implicit

template <class T> void MySwap( T& a, T& b ){ T c( a ); a = b; b = c;} int i, j; char k; MySwap( i, j ); //OK MySwap( i, k ); //Error, different Page : 37 Date : July 00 Automotive C Programming From C to C++

Constant Functions
A "read-only" member function that does not modify the object for which it is called. To declare a constant member function, place the const keyword after the closing parenthesis of the argument list. The const keyword is required in both the declaration and the definition. A constant member function cannot modify any data members or call any member functions that aren't constant. Example :
class Date { public: Date(int day); int getDay() const; void setDay( int day ); private: int day; }; int Date::getMonth() const { return day; } void Date::setMonth( int day ) { this->day = day; }

From C to C++

Automotive C Programming

Date : July 00 Page : 38

Mutable Data Member


If a data member is declared mutable, then it is legal to assign a value to this data member from a const member function. Syntax :
mutable <member-variable-declaration>;

Example :
class Date { public: Date(int d) : day (d), NbTimesRead (0) {} int getDay() const; void setDay( int day ); private: int day; mutable int NbTimesRead ; }; int Date::getMonth() const {NbTimesRead ++ ; return day; } void Date::setMonth( int day ) { this->day = day; } From C to C++ Automotive C Programming
Date : July 00 Page : 39

Reference to Objects
References to objects provide a convenient way to access objects by reference but use the same syntax required to access objects by value. References supports dynamic linkage Syntax :
<type> & <data>;

Examples :
int i = 1; int j = 2; int & ref_i = i; int & ref_j = j; ri = 3; // i now equal to 3 rj = ri; // j now equals i (3).
From C to C++ Automotive C Programming
Date : July 00 Page : 40

Reference
References can also be used for functions argument and return values
Examples :
void F( const int &IntValue ) {

int local = IntValue ; // ...


} int & F( void ) // return a reference {

// ...
}

From C to C++

Automotive C Programming

Date : July 00 Page : 41

From C to C++

auto bad_cast bad_typeid bool break case catch char class const const_cast continue default delete do double dynamic_cast else enum explicit extern false float for friend goto if inline int long mutable namespace

C++ Keywords

new operator private protected public register reinterpret_cast return short signed sizeof static static_cast struct switch template this throw true try type_info typedef typeid typename union unsigned using virtual void volatile while

Automotive C Programming

Date : July 00 Page : 42

Some C++ Coding Rules

From C to C++

Automotive C Programming

Date : July 00 Page : 43

Rules (1)
Do not defined the implementation of a method inside the declaration part of a class Do not declare any data member as public Do not declared any data nor function outside a class or outside a namespace Do not use the anonymous namespace Friends functions shall be used only in exceptional cases Friends classes shall not be used A class whose instantiation has to be avoid has to an abstract class or has to be declared all the constructors as protected Use multiple inheritance with care Do not use private inheritance Do not use protected inheritance Use constructors only for initialization purpose Use constructors initialization list to affect data member The destructor of a base class has to be virtual Non trivial object have to be designed thinking to basic operators : constructors, destructor, assignment, copy. Do not use malloc or free, but new and delete Use only one form of the new operator when building a data When defining the assignment operator, affect all the data members The assignment operator has to test the self assignment

From C to C++

Automotive C Programming

Date : July 00 Page : 44

Rules (2)
The analysis of using constant object has to be done Use constant functions to improvement robustness Use reference arguments instead of using value arguments Use reference arguments instead of using address arguments Declare constant the argument of a function which are not changed Use default values for parameters to simplify the call to function The default value shall be limited to constant and simple expressions Dont change inside a derived class a default value for a parameter in a function All the function overloading shall have the same semantic Analyze the interest to overload operators When a function return a pointer or a reference to a data member, then this return value has to be constant Use inline only when an optimization need is well identified Use a line per variable declaration Dont modify the value of this Dont use this to access data members, except for homonym problems Prefer local data to global data Prefer bloc declaration Initialize local data when declaring Initialize objects calling explicitly the constructors

From C to C++

Automotive C Programming

Date : July 00 Page : 45

Rules (3)
Multi threading require first an analysis of the compiler capabilities Resources allocated in a thread have to be freed in the same thread The interruption of a secondary thread by a primary thread have to be clean Avoid the use of reinterpret_cast Use explicit keyword when create a conversion constructor Prefer overload to user casting for function provided, excepted for basic types Use const_cast to convert constant expressions Use dynamic_cast to convert a pointer or a reference to a base class, to a pointer or a reference to a derived class Use exception mechanism or design a mechanism to handle errors Analysis of compiler capabilities have to done according to exceptions Use throw to specify the exceptions An exception shall not be caught by a function which is not able to treat it Define an exception hierarchy Forecast the non success of memory allocation The raise on an exception shall not drop the principle of resource recovery The raise of an exception shall not break the data integrity The raise of an exception inside a constructor shall not lead to a resource lack A destructor has to treat all the exception that shall occur A destructor shall not contain the throw instruction The end of the program shall no be link to an exception which is not treated

From C to C++

Automotive C Programming

Date : July 00 Page : 46

Rules (4)

Use meta programming techniques in order to combine efficiency and genericity Use function models instead of macro Use typename instead of class Avoid default values in templates Define precisely instantiation constraints for a model Use a naming rule for macro Dont use literal values in the code, and replace them with types constant Dont use macro for constant but enumeration or const keyword Dont change the literal values of an enumeration Overload the basic types in order to improve the portability Limit the definition of types : prefer classes Encapsulate type definition in classes or namespace Use bool type Use classed instead of structures Use unions only for optimized access to data

From C to C++

Automotive C Programming

Date : July 00 Page : 47

Rules (5)

Use STL Components Use STL String class to handle character strings Use STL input and output flow Use STL exception classes Use containers, iterators and algorithms The use of C files inside C++ SW has to be justified Prefer C++ comments Declare only one class in a file Use always the same order to define sections in a class (public, protected, private, friends) Use explicitly private keyword in a class

From C to C++

Automotive C Programming

Date : July 00 Page : 48

Das könnte Ihnen auch gefallen