12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open books for an open world

Embed Size (px)

Citation preview

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    1/22

    Programming Language Concepts Using C and

    C++/Object-Based Programming in C++

    Initially called C-with Classes, C++ has the class notion incorporated into the language. This is good news:

    some of the conventions and programming practices we had to adopt in C are now enforced by the compiler.Instead of having a header file containing the [intended] interface of an abstract data type, we now have a

    class definition in the header file, which is still intended to contain the interface; implementation details-such

    as utility functions and structure of the object- are now listed as private parts of the class definition, rather

    than deferring their definitions to the implementation file; constructor-like functions are replaced with true

    constructors that are implicitly called by the compiler-generated code.

    The above list can be extended with other examples. But the point remains the same: object-based

    programming is much easier in C++. The only pitfall is giving in to the simplicity of procedural paradigm and

    writing C++ code as plain old C. Apart from this, the following presentation should be a no-brainer for the

    initiate.[1]

    Contents

    1 Module

    1.1 Interface

    1.2 Implementation

    2 Function Overload Resolution

    2.1 Identification of the Candidate Functions

    2.2 Selection of the Viable Functions2.3 Argument Conversions

    2.4 Finding the Best Match

    3 Test Program

    3.1 Running the Program

    Module

    Interface

    Complex

    #i f ndef COMPLEX_HXX1.

    #def i ne COMPLEX_ HXX2.

    3.

    #i ncl ude 4.

    #i ncl ude 5.

    gramming Language Concepts Using C and C++/Object-Based Prog... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    22 20-11-2014 13:06

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    2/22

    usi ng names pace st d;6.

    7.

    namespace CSE224 {8.

    namespace Mat h {9.

    c l ass Compl ex {10.

    Access restriction to class members is specified by the labeled publ i c, pri vat e, and pr ot ect edsections within the class body. The keywords publ i c, pr i vat e, and pr ot ect edare called accessspecifiers.

    A publ i cmember is accessibleregardless of the point of referencefrom anywhere in the

    program. Proper enforcement of information hiding limits publ i cmembers of a class to functionsthat can be used by the general program to manipulate objects of the class type.

    1.

    A pr i vat emember can be accessed only by the member functions and friends of its class. A classthat enforces information hiding declares its data members as pr i vat e.

    2.

    A pr ot ect edmember behaves as a publ i cmember to a derived class and friends of its class, andbehaves as a pr i vat emember to the rest of the program.

    3.

    A class may contain multiple publ i c, pr ot ect ed, and pr i vat esections. Each section remains in effectuntil either another section label or the closing right brace of the class body is seen. If no access specifier is

    specified, by default the section immediately following the opening left brace of the class body is pr i vat e.

    publ i c:11.

    Definition: A default constructoris a constructor that can be invoked without user-specified arguments.

    In C++ this does not mean it cannot accept any arguments. It means only that a default value is associatedwith each parameter of the constructor. For example, each of the following represents a default constructor:

    Compl ex: : Compl ex( doubl e real Par t = 0. 0, doubl e i mPar t = 0. 0) { . . . } St ack: : St ack( i nt i ni t i al Capaci t y = 1) { . . . } Li st : : Li st ( voi d) { . . . }

    In C++, a constructor that can be invoked with a single parameter serves as a conversion operator. It helps

    us provide an implicit conversion from values of the constructor's parameter type to objects of the class,

    which is later used by the C++ compiler in the process calledfunction overload resolution.

    In the current class, passing a doubl eto the constructor will convert it to a Compl exobject with a zeroimaginary part. A very convenient tool! After all, isnt a real number a complex number with no imaginary

    part? However, this convenience may at times turn into a difficult-to-find bug. For instance, when passed a

    single doubl eargument, the following constructor will act like a conversion operator from doubl eto

    gramming Language Concepts Using C and C++/Object-Based Prog... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    22 20-11-2014 13:06

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    3/22

    Compl ex. It will likely produce unexpected results.

    Compl ex: : Compl ex( doubl e i mPar t = 0. 0, doubl e r eal Par t = 0. 0) { . . . }

    When invoked with a single argument, this constructor will create a Compl exobject with the real part set tozero. That is, Compl ex( 3. 0) will correspond to 3i, not 3! In order to avoid such unwanted conversionswhile keeping the parameter list the same, you must modify the signature with the expl i ci t keyword as inthe following.

    expl i ci t Compl ex: : Compl ex( doubl e i mpar t = 0. 0, doubl e real Par t = 0. 0) {. . . }

    Such a use disables implicit conversion through that constructor. Note the expl i ci t keyword can applyonly to constructors.

    Definition: An implicit type conversion done by the compiler is called coercion.

    Thanks to this implicit conversion done through the following constructor, whenever a function or an

    operator accepts a Compl exobject we will be able to pass an argument of type doubl e. Take the functionsignature on line 12, for instance. In addition to assigning a Compl exobject to another, this operator nowenables assignment of a doubl eto a Compl exobject. Because this doubl evalue is first [implicitly]

    converted to a Compl exobject and then assignment of this resulting object is performed.[2]

    Compl ex( doubl e = 0. 0, doubl e = 0. 0) ;12.

    Definition: A copy constructorinitializes an object with the copy of a second. Usually, it takes a formal

    parameter of a reference to a const object of the class.

    Note that this constructor, like the previous one, does not have a return type. This is not a typo!

    Constructor(s) (and the destructor, if there is any) of a class must not specify a return type, even that of

    voi d.

    Compl ex( const Compl ex&) ;13.

    In addition to function name overloading, C++ provides the programmer with an operator overloading

    facility. Overloaded operators allow objects of class type to be used with the built-in operators[3]defined in

    C++, allowing their manipulation to be as intuitive as that of built-in types.

    For overloading an operator, a function with a special name, which is formed by prefixing the word

    operator to the operator symbol, must be defined. It should be kept in mind that arity, precedence, andassociativity of the operator cannot be changed. For unary operators, the object receiving the message

    corresponds to the sole operand of the operator; for the rest, operand correspondence is established in a

    gramming Language Concepts Using C and C++/Object-Based Prog... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    22 20-11-2014 13:06

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    4/22

    left-to-right fashion. According to the following declaration, for instance, the receiver object corresponds to

    the left-hand side of the assignment while the [explicit] formal parameter corresponds to the right-hand side.

    Compl ex& operat or =( const Compl ex&) ;15.

    Thats right! Unlike C, C++ has type support for Boolean values. Unfortunately, it [C++] keeps supporting

    C-style semantics for Boolean expressions. In other words, you can still use integral values instead of

    Boolean values. But then again you can be a good boy and start using variables of type bool .

    bool oper at or==( const Compl ex&) ;16.

    Compl ex oper at or +( const Compl ex&) ;17.

    If assignment and addition operators are overloaded, users of the current class will naturally look for the

    corresponding overloaded compound assignment operator, +=.

    Compl ex& operat or +=( const Compl ex&) ;18.

    Compl ex oper at or - ( const Compl ex&) ;19.

    Compl ex& operat or - =( const Compl ex&) ;20.

    Modifying the explicit arguments to be constant is not a big deal. Simply insert somewhere before its position

    the const keyword and that will be all. But, what if we want to make the receiver objectthat is, theobject the message is being sent toconstant? This argument, passed as the implicit argument to the

    function, cannot be modified in a similar fashion. Following signatures are examples to how this can be done:

    put the const keyword after the closing parenthesis of the parameter list and it will be taken to stand forthe receiver object.

    Programmers can definethat is, provide the function bodythe member functions of a class either within

    the class (in the header file) or outside it (in the implementation file). Providing the function body in the

    header file may not be a good idea especially if it reveals implementation details [since this would meanviolating the information hiding principle]. Nevertheless, for functions as simple as the next two, it is not

    such a bad idea.

    gramming Language Concepts Using C and C++/Object-Based Prog... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    22 20-11-2014 13:06

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    5/22

    doubl e r eal ( voi d) const { return(_ r e) ; }22.

    doubl e i mag( voi d) const { return(_ i m) ; }23.

    24.

    pr i vat e:25.

    doubl e _ r e, _ i m;26.

    }; / / end of Compl ex cl ass def i ni t i on27.

    Next three functions are not members of the Compl exclass.[4]They are provided for complementing theclass definition. Making the case for the equality test operator should convince us about the other two as

    well. With two variables of two possible types, we have four combinations of equality tests. Equality test of

    two Compl exobjects and [thanks to the conversion provided through the constructor serving as auser-defined conversion function] a Compl exand a doubl eare provided as class member functions.Equality test of two doubl es is provided by the compiler. What is left is the test we need to make betweena doubl eand a Compl exnumber. This is certainly not provided by the compiler. It cannot be provided asa class member function, either. Because the left-hand side operand is a doubl eand we know that in theCompl exclass definition, thi sthe implicit parameteris a constant pointer to a Compl exobject. So,we need to follow a different path to provide this functionality: A plain old global function taking a doubl e

    and a Compl exnumber as parameters.

    ext ern bool oper at or==( doubl e, const Compl ex&) ;29.

    ext ern Compl ex oper at or +( doubl e, const Compl ex&) ;30.

    ext ern Compl ex oper at or - ( doubl e, const Compl ex&) ;31.

    An inline functionhas its source expanded into the program at each invocation point, thereby eliminating

    the overhead associated with a function call. It can therefore provide a significant performance gain

    provided that the function is invoked sufficiently many times.

    A member function defined within the class definitionsuch as r eal and i magis by default inline andsuch a function need not be further specified as inline. A member function defined outside the class body or

    any global function[5], on the other hand, must be specified to be so at its point of definition by prefixing the

    function prototype by the i nl i nekeyword and should be included within the header file containing theclass definition.

    Note that the inline specification is only a recommendation to the compiler. The compiler may choose to

    gramming Language Concepts Using C and C++/Object-Based Prog... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    22 20-11-2014 13:06

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    6/22

    ignore this recommendation, because the function declared inline is not a good candidate for expansion at

    the point of call. A recursive function cannot be completely expanded at the point of call. Likewise, a large

    function is likely to be ignored. In general, the inline mechanism is meant to optimize small, straight-line,

    frequently called functions.

    Notice the use of accessors, which actually contradicts our intentions of producing faster code by means of

    inlining. Accessing the fields directly, instead of through accessor functions, would have been faster and

    more in line with the i nl i nekeyword on the next line.[6]

    However, that's not possible. The object fields aredeclared to beas expectedpr i vat e, which means no one outside the class, including code of otherclasses within the same file can manipulate it. Well, as a matter of fact, there is an exception. By declaring

    certain functions and/or classes to have special rights through thefriend mechanism, one can gain direct

    access to the internals of a class. More on this is provided in the Exception Handling chapter.

    i nl i ne ost r eam& operat or

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    7/22

    } / / end of namespace CSE224

    53.

    #endi f54.

    Implementation

    Complex.cxx

    #i ncl ude 1.

    usi ng names pace st d;2.

    3.

    #i ncl ude " mat h/ Compl ex"4.

    5.

    namespace CSE224 {6.

    namespace Mat h {7.

    On certain occasions C++ compiler implicitly calls the default constructor. These are:

    All components of a heap-based array will be initialized using the default constructor of the

    component class.

    1.

    If not provided with an explicit constructor call in the member initialization list, sub-objects inherited

    will be initialized using the default constructor(s) of the base class(es).

    2.

    If not provided with an explicit constructor call in the member initialization list, non-primitive fields

    making up the object will be initialized using their default constructors.

    3.

    For this reason, as part of the design process, one should always give serious consideration to whether a

    default constructor is required or not.

    Thanks to the flexibility provided by default arguments, next three lines all use the same constructor.

    Compl ex c( 3, 5) ; / / c i s i ni t i al i zed t o 3. 0 + 5. 0i Compl ex r eal 3( 3) ; / / real 3 i s i ni t i al i zed t o 3. 0 + 0. 0i Compl ex zero; / / zer o i s i ni t i al i zed 0. 0 + 0. 0i

    As expected, C++ will coerce actual parameters of type i nt to doubl es and pass them to the appropriateconstructor.

    gramming Language Concepts Using C and C++/Object-Based Prog... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    22 20-11-2014 13:06

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    8/22

    Compl ex: :8.

    Compl ex( doubl e real Par t = 0. 0, doubl e i mPar t = 0. 0) {9.

    _ r e = real Par t ;10.

    _ i m = i mPar t ;11.

    } / / end of Compl ex: : Compl ex( doubl e, doubl e)12.

    If not provided with a copy constructor compiler will make a copy of an object by calling the copy

    constructor of each instance field. For primitive and pointer types, this means bitwise-copying the field.

    Definition: A class where all fields are bitwise-copied are said to support shallow copy.

    For our example, shallow-copying serves the purpose.[7]However, in cases where instance fields[8]of the

    object point to other objects or need to be skipped or treated specially, such as a password field, we may

    need more than a shallow copy. Consider the linked implementation of a list. Will it suffice to copy the head

    and tail indicators or shall we have to copy the items too? The answer is: it depends. If you want the same

    list to be shared then shallow copy is the way to go. Otherwise, you need to override the default behavior of

    the compiler. Once overridden, the compiler will always use this function whenever a copy has to be made.

    This constructor will be implicitly invoked whenever you pass an argument by value. Remember, an

    argument when passed by value will be copied on the run-time stack. Same can be said about returning an

    object from a function, which requires copying in the reverse direction. This very act of copying will be

    accomplished through the copy constructor. So, you should take some time deciding whether you need sucha constructor or not.

    Compl ex: :14.

    Compl ex( const Compl ex& r hs) {15.

    _ r e = r hs . _ r e;

    16.

    _ i m = r hs . _ i m;17.

    } / / end of Compl ex: : Compl ex( Compl ex&)

    18.

    Like other non-static member functions, overloaded operators take a pointer to the object on which the

    function is being applied. That is, given the declaration

    Compl ex c1( 3) , c2, r esul t ;

    . . . c1 + c2

    gramming Language Concepts Using C and C++/Object-Based Prog... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    22 20-11-2014 13:06

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    9/22

    can be seen as

    . . . c1. operator+( c2) . . .

    which can further be seen as

    operator +( &c1, c2)

    The corresponding function definition has an implicit first formal parameter. This formal parameter namedthis can be used to refer to the object the message is being sent to. So, given the function definition

    Cl assName: : Funct i onName( For mal - Par- Li st ) { . . . }

    the compiler internally makes a function call to

    Funct i onName( Cl assName *const t hi s, Formal - Par- Li st ) { . . . }

    whenever

    c1. Funct i onName( Act ual - Par - Li st ) ;

    is used in the code by transforming it into

    Funct i onName( &c1, Act ual - Par- Li s t ) ;

    Note that it is the pointer that is declared to be constant, not the contents of the memory pointed to by the

    pointer. The programmer can, directly or indirectly, change the objects memory but cannot change the

    object that the function is being applied on.

    Following function definition overloads the assignment operator. Such an operator is used to modify the

    contents of an already existing object with that of another.[9]Unless provided with an overridden version,the compilersimilar to the copy constructor casewill call the default assignment operator of each and

    every field of the object. Otherwise, it will use one of the functions you provide. As to whether you need to

    override, considerations listed in the case of copy constructor apply and one should pay special care for

    making the right decision.

    Reason why we use Compl ex&as the return value [and parameter] type of the function is to facilitate the

    concatenation of the assignment operators in the least expensive and easiest way possible.[10]For instance, it

    is possible to have a statement like

    a = b = c;

    This statement is carried out by first assigningcto band then bto a. That is, bwill first be used as theobject to which the assignment message is sent and then as the parameter of another assignment message

    that is sent to a.

    Compl ex& Compl ex: :20.

    oper at or =( const Compl ex& r hs) {21.

    gramming Language Concepts Using C and C++/Object-Based Prog... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    22 20-11-2014 13:06

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    10/22

    Next two lines can be written without the keyword t hi s. Because all unqualified references to objectsmemory is assumed to belong to the object pointed to by thi s. So, it can be rewritten as:

    _re = rhs. _re; _i m = rhs. _i m;

    Note also the use of - >. This is another indication of the fact that this is not the receiver object itself butrather a constant pointer to it.

    t hi s - >_r e = r hs . _ r e;22.

    t hi s - >_ i m = r hs . _ i m;23.

    24.

    return( * t hi s) ;

    25.

    } / / end of Compl ex: : Compl ex& oper at or =( const Compl ex&)26.

    27.

    bool Compl ex: :28.

    oper at or==( const Compl ex& r hs) {29.

    return( t hi s- >_r e == r hs . _ re && t hi s- >_ i m == r hs . _ i m) ;30.

    } / / end of bool Compl ex: : oper ator ==( const Compl ex&)31.

    32.

    Compl ex Compl ex: :33.

    oper at or+( const Compl ex& r hs) {34.

    return( Compl ex(_ r e + r hs. _ r e, _ i m + r hs . _ i m) ) ;35.

    } / / end of Compl ex Compl ex: : oper at or +( const Compl ex&)36.

    37.

    Compl ex& Compl ex: :38.

    oper at or+=( const Compl ex& r hs) {39.

    t hi s - >_r e += r hs . _ r e;40.

    t hi s - >_ i m += r hs . _ i m;

    41.

    42.

    return( * t hi s) ;43.

    gramming Language Concepts Using C and C++/Object-Based Prog... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    f 22 20-11-2014 13:06

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    11/22

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    12/22

    } / / end of namespace CSE224

    Function Overload Resolution

    As was mentioned in the annotations before the signature of the default constructor in the header file,function overload resolution is about figuring out the function to be invoked. A process ending with one of

    three possible outcomessuccess, ambiguity, and no matching functiona function call is resolved in three

    steps.

    Identification of the Candidate Functions

    First step of function overload resolution involves identification of functions that have the same name with

    the function being called and are visible at the point of the call. This set of functions are also called

    candidate functions. An empty set of candidate functions gives rise to a compile-time error.

    Use of types defined in namespaces as argument types and/or importing identifiers from namespaces may

    lead to an increase in the size of this set.

    Example: Effect of introducing a namespace.

    namespace ns { . . . cl ass Type { . . . }; voi d f(Type t ) ; . . .

    };

    voi d f( i nt i ) { . . . }voi d f( doubl e d) { . . . }. . .

    usi ng namespace ns;. . .f( . . . ) ;

    Function call on the last line will lead to a set of size three: ns: : f( ns: :Type) , f( i nt ) , andf( doubl e) . Without the using directive ns: : f( ns: :Type) will not be visible and therefore will not beincluded in the candidate functions set. However, replacing the usi ngdirective with the following codesequence will again cause this function to be included in the set.

    . . . ns: :Type t ; . . . f( t ) ; . . .

    As will later be discussed in the Inheritance chapter, depending on the language, introduction of a new scope

    may affect the set of candidate functions differently. In Java, for instance, the new set is formed by taking a

    union of the former set and the set introduced by the new scope; in case of identical signatures methods of

    gramming Language Concepts Using C and C++/Object-Based Prog... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    f 22 20-11-2014 13:06

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    13/22

    the new scope shadow those found in the former. In C++, however, a function with a name clashing with one

    found in the former set replaces all function signatures having this name.

    Example: Effect of inheritance in Java on the set of candidate functions.

    B.java

    publ i c cl ass B {

    . . . publ i c voi d f( i nt ) { } publ i c voi d f( i nt , i nt ) { } . . . } / / end of cl ass B

    D.java

    public class D extends B { . . . public void f( St r i ng) { } . . . } // end of class D

    Users of an object of class Dcan use one of three methods, all named f: B. f( int) , B. f( int, int) ,and D. f( St r i ng) .

    Selection of the Viable Functions

    Second step consists of selecting the callable functions from the non-empty set formed in the first phase.

    This requires elimination of functions that do not match the number of arguments and their types. The set of

    functions obtained by the end of this phase is called the viable functions. An empty set of viable functions

    means no matching function and causes a compile-time error to be emitted.

    Note that we are not seeking a perfect match here. As far as the number of arguments is concerned, default

    values increase the size of this set. For instance, a function call with a single argument can be directed not

    only to a function with a single parameter but also to functions with nparameters all of which, except the

    first, are guaranteed to have a default value. Similarly, for argument types, conversions that can be applied

    on the arguments are also considered. As an example to this, a char argument can be passed to acorresponding parameter of type char , shor t , i nt , and so on.

    Example: Selection of viable functions in C++

    voi d f( i nt i , i nt i 2 = 0) { . . . }1.

    voi d f( char ) { . . . }2.

    voi d f( doubl e d, f l oat f) { . . . }3.

    voi d f( Compl ex c ) { . . . }

    4.

    . . .

    5.

    shor t s;6.

    gramming Language Concepts Using C and C++/Object-Based Prog... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    f 22 20-11-2014 13:06

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    14/22

    . . .7.

    f( s) ;8.

    . . .9.

    Invocation of fon line 8 will lead to a set of size two: f( char ) and f( i nt , i nt=) . In case Compl exclass may have a constructor that can be used to convert a shor t to a Compl exobject size of this set isincreased to three.

    For programmers from safer languages such as Java or C#, inclusion of f( char ) in this set may come as asurprise. Being a narrowing conversion, passing a shor t argument to a char parameter will probably leadto information loss and therefore is deemed to be a violation of the contract by these languages. In order to

    make this happen one must explicitly cast the argument to char . It is an entirely different story in C++,however. A C++ compiler will happily consider thisnot explicitly casting the argumentas a keystroke

    saving activity and accept it as a viable function. If this happens to be the one and only viable function,

    function call in question will be dispatched to f( char ) .

    Argument Conversions

    This brings us to the topic of probable conversions applicable on an argument. In addition to an exact

    match[11], a C++ compiler expands the set of viable functions by applying a series of conversions on the

    arguments. These fall in two different categories: exact matchand type conversion.

    The exact match conversions are minor ones and can further be treated in four subgroups:

    lvalue-to-rvalue conversion: Seeing argument passing as a special case of assignment, where argument

    is assigned to the corresponding parameter, this conversion basically fetches the value in the argument

    and copies it into the parameter.

    1.

    Array-to-pointer conversion: An array is passed as a pointer to its first element. Note this and the

    following conversion are basically a part of the C/C++ language.

    2.

    Function-to-pointer conversion: Similar to the previous item, a function identifier, when passed as an

    argument, is transformed into a pointer to function.

    3.

    Qualification conversion: Applicable only to pointer types, this conversion transforms a plain pointer

    type by modifying it with either one or both of const [12]and vol at i l emodifiers. It should be

    noted that no type conversion takes place in the case of an argument being passed to a parameter ofthe same type with one or two of these modifier.

    4.

    Example: Exact match conversion in C++.

    i nt i a[ 20] ;1.

    i nt * i a2 = new i nt [ 30] ;2.

    . . .3.

    voi d f( i nt *ar r ) { . . . } / / coul d have been voi d f ( i nt ar r [ ] ) { . . . }4.

    5.

    gramming Language Concepts Using C and C++/Object-Based Prog... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    f 22 20-11-2014 13:06

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    15/22

    voi d g( const i nt i ) { . . . }

    . . .6.

    f( i a) ; / / won' t get any t r eat ment di f f erent t han f ( i a2) . Both wi l l be r anked equal7.

    . . .8.

    g( i a[ 3] ) ; / / wi l l be di spat ched to g( const i nt ) wi thout any [ qual i f i cat i on] conver si on9.

    On line 7 array argument is converted to and passed as a pointer to its first element. On line 9, a

    non-constant argument is passed by value to a constant parameter of the same type. Since any changes

    made in a parameter that receives its initial value using call-by-value are not reflected back to the argument

    and const parameters never changelet alone change and reflect this onto the corresponding argument

    passing an i nt argument to a const i nt parameter does not require any conversion at all.

    Second category of argument conversions, type conversions, can be examined in two groups:promotionsand standard conversions. The former group, also called widening conversions, contain conversions that can

    be performed without information loss. These include the following:

    An argument of type bool , char , unsi gned char , and short is promoted to i nt . If thecompiler used supports a larger size for i nt , unsi gned shor t is also promoted to i nt . Otherwiseit is promoted to unsi gned i nt .

    1.

    An argument of type f l oat is promoted to doubl e.2.An enumeration type is promoted to one of i nt , unsi gned i nt , l ong, or unsi gned l ong.Decision is made by choosing the smallest possible type that can represent all values in the

    enumeration.

    3.

    Second group of type conversions, standard conversions, are divided into five:

    i nt -to-l ongconversion and narrowing integral conversions.1.doubl e-to-f l oat conversion.2.Conversions made between floating point and integral types, such as f l oat -to-i nt , i nt -to-doubl e, and char -to-doubl e.

    3.

    Conversion of 0 to a pointer type and conversion of any pointer type to voi d*.4.Conversions from integral types, floating point types, enumeration types, or pointer types to bool .5.

    Note that this long list of rules contains quite a few details that are due to "low-level" nature and systems-

    programming aspect of C++, which were inherited from C. For example, having no type to hold logical

    values, C takes care of it by adopting a convention used in low-level programming: zero stands for false and

    anything else is interpreted to be true. Hence is the transformation from other types to bool . Similarly,

    architectures tend to provide better support for word size data, which in C/C++ is called i nt .[13]A typicalexample to this is the amount of adjustment made while pushing data on the hardware stack. Unless the

    compiler packs them, all data pushedread it as "all arguments passed"smaller than or equal to the word

    sizeread it as i ntwill be adjusted to a word boundary. This basically means all such data will bewidened to the word size, which explains the first item of promotions. Add to this the environment-

    dependent size of integral types and the complexity introduced by having two versions (si gnedandunsi gned) you can understand why it suddenly turns into a nightmare.

    Example: Concerisons in Java.

    ConversionInJava.java

    gramming Language Concepts Using C and C++/Object-Based Prog... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    f 22 20-11-2014 13:06

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    16/22

    publ i c cl ass Conver si onI nJ ava { publ i c st at i c voi d mai n( St r i ng[ ] ar gs) { shor t s = 3;

    f( s) ; } / / end of voi d mai n( St r i ng[ ] )

    pr i vat e stat i c voi d f( i nt i ) { Syst em. out . pr i nt l n( I n voi df( i nt) . . . ) ; }

    pr i vat e stat i c voi d f( l ong l ) { Syst em. out . pr i nt l n( I n voi df( l ong) . . . ) ; } } / / end of cl ass Conver si onI nJ ava

    Compiling and running this program will cause the message in f( i nt ) to be output on the standard output.Because, in Java, an argument is always promoted to the closest type.

    In the process of conversion C++ compiler can apply either one of two sequences. In the first sequence,

    which is called the standard conversion sequence, it is permitted to apply zero or one exact match

    conversionwith the exception of qualification conversionfollowed by zero or one promotion or standard

    conversion, which may further be followed by zero or one qualification conversion. Second sequence

    involves application of a user-defined conversion function, which may be preceded and followed by a

    standard conversion sequence. If there need be this this sequence can be applied twice.

    Finding the Best Match

    In the final step of resolving the function call C++ compiler picks the viable function with the best match.

    Two criteria are used in determining the best match: conversions applied to the arguments of the best matchfunction are no worse than the conversions necessary to call any other viable function; conversions on some

    arguments are better than the conversions necessary for the same arguments when calling the other viable

    functions. In case there turns out to be no such function, call is said to be ambiguous and causes a

    compile-time error.

    In finding the best match compiler ranks viable functions obtained in the previous step. According to this

    ranking, an exact match conversion is better than a promotion and a promotion is better than a standard

    conversion. A viable function is given the rank of the lowest ranked conversion used in transforming the

    arguments to the corresponding parameters.

    Test Program

    Next program, apart from providing examples of the function overload resolution process, shows that in C++

    one can create objects in all three data regions. In some object-oriented programming languages, such as

    Java, objects are always created in the heap. This "limitation" of Java- or put differently, this "freedom"

    offered by C++- can be attributed to the language design philosophy. Being a direct descendant of C, C++

    provides alternatives and expects the programmer to choose the right one. Also a descendant of C, albeit a

    more distant one, Java tends to provide a simpler framework with fewer alternatives.

    In this case, C++ offers programmers an alternative that does away with using pointers. Like variables of a Cstruct or objects of a value type in C#, one can directly manipulate objects of classes. In other words,manipulating objects indirectly by means of handles is not the only option. This means less space for the

    object. However, polymorphismand therefore, object-orientationis not an option anymore. After all,

    polymorphism requires that same message is dispatched to probably different subprogram definitions

    gramming Language Concepts Using C and C++/Object-Based Prog... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    f 22 20-11-2014 13:06

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    17/22

    depending on the dynamic type of the object, which means we should be able to use the same identifier to

    refer to objects of different types. This further implies that memory required for the object indicated by the

    identifier may change. Since the static data region deals with data of fixed size we cannot possibly put the

    object in this part of the program memory. Similarly, size of memory allocated on the run-time stack should

    be known beforehand by the compiler, run-time stack is also out of question. We must conjure up a solution

    where both parties are satisfied: compiler is given a fixed-size entity, while the variable-size object

    requirement of inheritance is met. This is accomplished by creating objects on the heap, which is the only

    place left, and manipulating it through an intermediary. Enter the object handle!

    So, enabling polymorphism is possible only if objects are created on the heap and manipulated through

    pointers. That explains why Javalike any other programming language claiming to be object-oriented

    creates objects the way it does. But it doesn't offer any explanations for the lack of creating objects the

    C++ way. Answering another questionwhat benefit we get when we create objects the C++ waywill

    provide the explanation: We get faster and object-basednot object-oriented!solutions. Since

    polymorphism is out of question and therefore dynamic dispatch is not required anymore, all our function

    calls can be statically dispatched, which by the way is the default in C++. But then it starts to be a little

    confusing with all these paradigms. In addition to procedural programming, thanks to its C heritage, and

    object-oriented programming, we now have object-based programming. What makes things worse is default

    mode of programing in C++, since default dispatch type is static, is object-based. In Java, the defaultdispatch type is dynamic and therefore default programming paradigm is object-oriented. This means the

    programmer, expecting to do some object-oriented programming, is not confused with the presence of

    alternatives; she does not need to tell the compiler that she wants to do object-oriented programming. Add to

    this the utilization of object-oriented paradigm in realizing the open-closed principle[14], this seems to be a

    safer choice for producing extensible software.

    Complex_Test.cxx

    #i ncl ude 1.

    #i ncl ude 2.

    usi ng names pace st d;3.

    4.

    #i ncl ude " mat h/ Compl ex"5.

    usi ng CSE224: : Mat h: : Compl ex;6.

    The following line creates an object of class Compl exin the static data region. This object will thereforeexist throughout the entire execution of the program and its allocation/deallocation will be among the

    responsibilities of the compiler. This line could have been written as Compl ex c( 5) ; or Compl ex c =Compl ex( 5) ; .

    Note that the second form is possible only when we pass one argument to the constructor.

    gramming Language Concepts Using C and C++/Object-Based Prog... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    f 22 20-11-2014 13:06

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    18/22

    Compl ex c = 5;8.

    9.

    i nt mai n( voi d) {

    10.

    Next four instantiations create four Compl exobjects on the run-time stack. Each time a subprogram isinvoked or a block is entered, objects local to the subprogram/block will be created and allocated on the

    run-time stack. Upon exit from the subprogram/block, the objects will be automatically deallocated through

    changing the value of the stack pointer, which points to the topmost frame on the run-time stack. So, the

    lifetimes of local objects are limited to the block that they are defined in.[15]

    Note the fourth object is created through the use of the copy constructor. By virtue of this statement, c3andc4both have the same object-memory configurations. But realize they are not the same objects.

    Compl ex c1( 3, - 5) , c2( 3) , c3( 0, 5) , c4( c3) ;11.

    cout

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    19/22

    cout

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    20/22

    Assuming left-to-right evaluation order [for pedagogical purposes] next line will be carried out as follows:

    i is promoted to doubl e.1.Using operator- ( doubl e, const Compl ex&) c1is subtracted from i , which is now adoubl evalue. In the process, c1is first converted from Compl exto const Compl ex.

    2.

    Using Compl ex: : operator+( const Compl ex&) c2is added to the result obtained in step 2.As in the previous step, c2is first qualified with const .

    3.

    Utilizing the constructor with default argument values, compiler converts dto a Compl exobject.4.Using Compl ex: : operator - ( const Compl ex&) subtract d, now an object of Compl ex, fromthe result obtained in step 3.

    5.

    Finally, the value obtained in step 5 is assignedby means of the programmer provided assignment

    operator [Compl ex: : operat or=( const Compl ex&) ]to the memory region pointed to byr esul t .

    6.

    *resul t = i - c1 + c2 - d;23.

    cout

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    21/22

    That is, we have the relevant information in the object itself, not pointers to some variable-sized information

    lying somewhere in the heap. The compiler can deal with such fixed size information by simply freeing the

    region pointed to by the argument of the del et eoperator. But when it comes to dealing with variable-sizedinformation or outside resources, the programmer must provide some extra help. And this is what we have

    the destructor for. Absence of this assistance means wasting precious system resources, which is very likely

    to lead to a crash. For this reason, one should seriously consider whether a destructor is needed or not.

    Definition: Orthodox Canonical Formis a set of functions one should give special treatment in the process

    of implementing a class. These functions include: default constructor, copy constructor, assignment operator,

    equality-test operator, and destructor.

    It should be underlined that automatic garbage collection does not relieve us from considering the need for a

    destructor-like function. A garbage collector solves part of the problem: it deals with deallocation of heap

    memory. We now do not have to think about whether data members are inline or not. All pertaining to heap

    data will be taken care of by the garbage collector. But what about other outside resources? They still need

    to be handled by the programmer in a destructor-like function, called finalizer.

    Definition: In languages with automatic garbage collection, the implicitly called special function needed for

    cleaning up the non-heap outside resources utilized by an object is calledfinalizer.

    As a final note, one must keep in mind that intimate relation between the destructor and the heap does not

    mean the destructor is called only upon deallocating a heap object. Even when the object in question does

    not have any outside resources, the destructor is calledthis time, implicitly by the compiler-synthesized

    codeupon exiting a block (for local objects) or at the end of a program (for global or static local objects).

    del et e resul t ;27.

    cout

  • 8/10/2019 12 Programming Language Concepts Using C and C++_Object-Based Programming in C++ - Wikibooks, open bo

    22/22

    g++ - I ~/i ncl ude o Compl ex_Test Compl ex_Test . cxx Compl ex. o

    . /Compl ex_Test c: 5 c1: (3- 5i ) c2: 3 c3: 5i c4: 5i d: 3 i : 5

    d + c1 = (6- 5i ) c1 + i = (8- 5i )

    *r esul t = i - c1 + c2 - d = (2+5i ) *r esul t += c3 = (2+10i ) *r esul t - = d = (- 1+10i ) Equal i t y test oper at or . . . c1 - c2 + c3 ?= 0. . . OK c ?= i . . . OK

    == Not es =={{Ref l i st}}

    {{BookCat}}

    As a matter of fact, this is a rather slimmed-down and incomplete implementation, which lacks many

    features youd normally be looking for in a C++ class.

    1.

    More on conversions is provided in here.2.

    The following operators cannot be overloaded: ?: (if-then-else operator), . (member selectionoperator), . * (pointer-member selection operator), : : (scope operator).

    3.

    It should be noted that the following operators can be overloaded only as class member functions: =(assignment operator), [ ] (subscript operator), ( ) (function call operator), - >(member accessoperator).

    4.

    That would be any function not defined inside a class.5.ref!!!6.

    In other words, we actually duplicate the code that would have been synthesized by the compiler.7.

    There is no need to copy static fields.8.

    ref99.

    ref1010.

    ref1111.

    ref1212.

    ref1313.

    ref1414.

    ref1515.

    ref1616.

    Retrieved from "http://en.wikibooks.org

    /w/index.php?title=Programming_Language_Concepts_Using_C_and_C%2B%2B/Object-

    Based_Programming_in_C%2B%2B&oldid=2717723"

    This page was last modified on 24 October 2014, at 16:19.

    Text is available under the Creative Commons Attribution-ShareAlike License.; additional terms may

    apply. By using this site, you agree to the Terms of Use and Privacy Policy.

    gramming Language Concepts Using C and C++/Object-Based Prog... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...