Beruflich Dokumente
Kultur Dokumente
Automotive C Programming
July 2000
From C to C++
Automotive C Programming
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
Class Overview
The class Public part (data and code)
From C to C++
Automotive C Programming
Class Exemple
Point public : int Get_x (); int Get_y () ; int Norm () ; private : int x ; int y ;
From C to C++
Automotive C Programming
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
From C to C++
Automotive C Programming
From C to C++
Automotive C Programming
From C to C++
Automotive C Programming
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
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
From C to C++
Automotive C Programming
Base class
is a
Derived class
From C to C++
Automotive C Programming
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 ;
From C to C++
Automotive C Programming
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
From C to C++
Automotive C Programming
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
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
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
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
From C to C++
Automotive C Programming
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
From C to C++
Automotive C Programming
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
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
Conversion Functions
Complement to Conversion by constructors Syntax operator <conversion-type-name> () Example : operator int () { ...}
From C to C++
Automotive C Programming
New Operator
Called when objects are allocated Two syntaxes
simple arrays
From C to C++
Automotive C Programming
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
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
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
Matching Mechanism
From C to C++
Automotive C Programming
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
Nonredefinable Operators
. .* :: ?: # ##
Member selection Pointer-to-member selection Scope resolution Conditional Preprocessor symbol Preprocessor symbol
From C to C++
Automotive C Programming
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
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 ) {
// ...
}
From C to C++
Automotive C Programming
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
From C to C++
Automotive C Programming
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
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
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
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
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