Wednesday, 15 May 2013

C++ PROGRAMING FOR BEGINNERS. PT1



Am going to take you step by step on C++ programming. I hope it shades some light on some of you difficulties. We'll begin from the basics;

2.1 What is C++? 
C++ is a general-purpose programming language with a bias towards systems programming that – is a better C, – supports data abstraction, – supports object-oriented programming, and – supports generic programming. This chapter explains what this means without going into the finer details of the language defini- tion. Its purpose is to give you a general overview of C++ and the key techniques for using it, not to provide you with the detailed information necessary to start programming in C++. If you find some parts of this chapter rough going, just ignore those parts and plow on. All will be explained in detail in later chapters. However, if you do skip part of this chapter, do yourself a favor by returning to it later. Detailed understanding of language features – even of all features of a language – cannot com- pensate for lack of an overall view of the language and the fundamental techniques for using it.








2.2 Programming Paradigms
Object-oriented programming is a technique for programming – a paradigm for writing ‘‘good’’ programs for a set of problems. If the term ‘‘object-oriented programming language’’ means any- thing, it must mean a programming language that provides mechanisms that support the object- oriented style of programming well. There is an important distinction here. A language is said to support a style of programming if it provides facilities that make it convenient (reasonably easy, safe, and efficient) to use that style. A language does not support a technique if it takes exceptional effort or skill to write such pro- grams; it merely enables the technique to be used. For example, you can write structured programs in Fortran77 and object-oriented programs in C, but it is unnecessarily hard to do so because these languages do not directly support those techniques. Support for a paradigm comes not only in the obvious form of language facilities that allow direct use of the paradigm, but also in the more subtle form of compile-time and/or run-time checks against unintentional deviation from the paradigm. Type checking is the most obvious example of this; ambiguity detection and run-time checks are also used to extend linguistic support for para- digms. Extra-linguistic facilities such as libraries and programming environments can provide fur- ther support for paradigms. One language is not necessarily better than another because it possesses a feature the other does not. There are many examples to the contrary. The important issue is not so much what features a language possesses, but that the features it does possess are sufficient to support the desired pro- gramming styles in the desired application areas: [1] All features must be cleanly and elegantly integrated into the language. [2] It must be possible to use features in combination to achieve solutions that would otherwise require extra, separate features. [3] There should be as few spurious and ‘‘special-purpose’’ features as possible. [4] A feature’s implementation should not impose significant overheads on programs that do not require it. [5] A user should need to know only about the subset of the language explicitly used to write a program. The first principle is an appeal to aesthetics and logic. The next two are expressions of the ideal of minimalism. The last two can be summarized as ‘‘what you don’t know won’t hurt you.’’ C++ was designed to support data abstraction, object-oriented programming, and generic pro- gramming in addition to traditional C programming techniques under these constraints. It was not meant to force one particular programming style upon all users. The following sections consider some programming styles and the key language mechanisms supporting them. The presentation progresses through a series of techniques starting with procedu- ral programming and leading up to the use of class hierarchies in object-oriented programming and generic programming using templates. Each paradigm builds on its predecessors, each adds some- thing new to the C++ programmer’s toolbox, and each reflects a proven design approach. The presentation of language features is not exhaustive. The emphasis is on design approaches and ways of organizing programs rather than on language details. At this stage, it is far more important to gain an idea of what can be done using C++ than to understand exactly how it can be achieved.

2.3 Procedural Programming 

The original programming paradigm is:
Decide which procedures you want; use the best algorithms you can find.
The focus is on the processing – the algorithm needed to perform the desired computation. Lan- guages support this paradigm by providing facilities for passing arguments to functions and return- ing values from functions. The literature related to this way of thinking is filled with discussion of ways to pass arguments, ways to distinguish different kinds of arguments, different kinds of func- tions (e.g., procedures, routines, and macros), etc. A typical example of ‘‘good style’’ is a square-root function. Given a double-precision floating-point argument, it produces a result. To do this, it performs a well-understood mathemati- cal computation:
dd o ouu b bll e e ss q qrr t t(dd o ouu b bll e e aa r rgg ) { // code for calculating a square root }
vv o oii d d ff () { dd o ouu b bll e e rr o ooo t t22 = ss q qrr t t(22 ); // ... }
Curly braces, { }, express grouping in C++. Here, they indicate the start and end of the function bodies. The double slash, // , begins a comment that extends to the end of the line. The keyword vv o oii d d indicates that a function does not return a value. From the point of view of program organization, functions are used to create order in a maze of algorithms. The algorithms themselves are written using function calls and other language facili- ties. The following subsections present a thumb-nail sketch of C++’s most basic facilities for expressing computation.
2.3.1 Variables and Arithmetic 
Every name and every expression has a type that determines the operations that may be performed on it. For example, the declaration
ii n ntt  i inn c chh ;
specifies that ii n ncc h h is of type ii n ntt ; that is, ii n ncc h h is an integer variable. A declaration is a statement that introduces a name into the program. It specifies a type for that name. A type defines the proper use of a name or an expression. C++ offers a variety of fundamental types, which correspond directly to hardware facilities. For example:
The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.
24 A Tour of C++ Chapter 2
bb o ooo l l // Boolean, possible values are true and false cc h haa r r // character, for example, ’a’, ’z’, and ’9’ ii n ntt // integer, for example, 1, 42, and 1216 dd o ouu b bll e e // double-precision floating-point number, for example, 3.14 and 299793.0
A cc h haa r r variable is of the natural size to hold a character on a given machine (typically a byte), and an ii n ntt variable is of the natural size for integer arithmetic on a given machine (typically a word). The arithmetic operators can be used for any combination of these types:
+ // plus, both unary and binary - // minus, both unary and binary * // multiply / // divide % // remainder
So can the comparison operators:
== // equal != // not equal < // less than > // greater than <= // less than or equal >= // greater than or equal
In assignments and in arithmetic operations, C++ performs all meaningful conversions between the basic types so that they can be mixed freely:
vv o oii d d ss o omm e e__ ff u unn c ctt i ioo n n() // function that doesn’t return a value { dd o ouu b bll e e dd = 22 .22 ; // initialize floating-point number ii n ntt  i i = 77 ; // initialize integer dd = dd +ii ; // assign sum to d ii = dd *ii ; // assign product to i }
As in C, = is the assignment operator and == tests equality.
2.3.2 Tests and Loops [tour.loop]
C++ provides a conventional set of statements for expressing selection and looping. For example, here is a simple function that prompts the user and returns a Boolean indicating the response:
bb o ooo l l aa c ccc e epp t t() { cc o ouu t t << "DD o o yy o ouu  w waa n ntt  t too  p prr o occ e eee d d (yy  o orr  n n)?\\ n n"; // write question
cc h haa r r aa n nss w wee r r = 00 ; cc i inn >> aa n nss w wee r r; // read answer
ii f f (aa n nss w wee r r == ´yy ´) rr e ett u urr n n tt r ruu e e; rr e ett u urr n n ff a all s see ;
}
The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.
Section 2.3.2 Tests and Loops 25
The << operator (‘‘put to’’) is used as an output operator; cc o ouu t t is the standard output stream. The >> operator (‘‘get from’’) is used as an input operator; cc i inn is the standard input stream. The type of the right-hand operand of >> determines what input is accepted and is the target of the input opera- tion. The \\ n n character at the end of the output string represents a newline. The example could be slightly improved by taking an ‘n’ answer into account:
bb o ooo l l aa c ccc e epp t t22 () { cc o ouu t t << "DD o o yy o ouu  w waa n ntt  t too  p prr o occ e eee d d (yy  o orr  n n)?\\ n n"; // write question
cc h haa r r aa n nss w wee r r = 00 ; cc i inn >> aa n nss w wee r r; // read answer
ss w wii t tcc h h (aa n nss w wee r r) { cc a ass e e ´yy ´: rr e ett u urr n n tt r ruu e e; cc a ass e e ´nn ´: rr e ett u urr n n ff a all s see ; dd e eff a auu l ltt : cc o ouu t t << "II ´ll l l tt a akk e e tt h haa t t ff o orr  a a nn o o.\\ n n"; rr e ett u urr n n ff a all s see ; }
}
A switch-statement tests a value against a set of constants. The case constants must be distinct, and if the value tested does not match any of them, the dd e eff a auu l ltt is chosen. The programmer need not provide a dd e eff a auu l ltt . Few programs are written without loops. In this case, we might like to give the user a few tries:
bb o ooo l l aa c ccc e epp t t33 () { ii n ntt  t trr i iee s s = 11 ; ww h hii l lee (tt r rii e ess < 44 ) { cc o ouu t t << "DD o o yy o ouu  w waa n ntt  t too  p prr o occ e eee d d (yy  o orr  n n)?\\ n n"; // write question cc h haa r r aa n nss w wee r r = 00 ; cc i inn >> aa n nss w wee r r; // read answer
ss w wii t tcc h h (aa n nss w wee r r) { cc a ass e e ´yy ´: rr e ett u urr n n tt r ruu e e; cc a ass e e ´nn ´: rr e ett u urr n n ff a all s see ; dd e eff a auu l ltt : cc o ouu t t << "SS o orr r ryy , II  d doo n n´tt  u unn d dee r rss t taa n ndd  t thh a att .\\ n n"; tt r rii e ess = tt r rii e ess + 11 ; }
} cc o ouu t t << "II ´ll l l tt a akk e e tt h haa t t ff o orr  a a nn o o.\\ n n"; rr e ett u urr n n ff a all s see ;
}
The while-statement executes until its condition becomes ff a all s see .
The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.
26 A Tour of C++ Chapter 2
2.3.3 Pointers and Arrays [tour.ptr]
An array can be declared like this:
cc h haa r r vv [11 0 0];  / / array of 10 characters
Similarly, a pointer can be declared like this:
cc h haa r r* pp ; // pointer to character
In declarations, [] means ‘‘array of’’ and * means ‘‘pointer to.’’ All arrays have 00 as their lower bound, so vv has ten elements, vv [00 ]...vv [99 ]. A pointer variable can hold the address of an object of the appropriate type:
pp = &vv [33 ];  / / p points to v’s fourth element
Unary & is the address-of operator. Consider copying ten elements from one array to another:
vv o oii d d aa n noo t thh e err __ ff u unn c ctt i ioo n n() { ii n ntt  v v11 [11 0 0]; ii n ntt  v v22 [11 0 0]; // ... ff o orr (ii n ntt  i i=00 ; ii <11 0 0; ++ii ) vv 1 1[ii ]=vv 2 2[ii ]; }
This for-statement can be read as ‘‘set ii to zero, while ii is less than 11 0 0, copy the ii th element and increment ii .’’ When applied to an integer variable, the increment operator ++ simply adds 11 .

2.4 Modular Programming [tour.module]
Over the years, the emphasis in the design of programs has shifted from the design of procedures and toward the organization of data. Among other things, this reflects an increase in program size. A set of related procedures with the data they manipulate is often called a module. The program- ming paradigm becomes:
Decide which modules you want; partition the program so that data is hidden within modules.
This paradigm is also known as the data-hiding principle. Where there is no grouping of proce- dures with related data, the procedural programming style suffices. Also, the techniques for design- ing ‘‘good procedures’’ are now applied for each procedure in a module. The most common exam- ple of a module is the definition of a stack. The main problems that have to be solved are: [1] Provide a user interface for the stack (e.g., functions pp u uss h h() and pp o opp ()). [2] Ensure that the representation of the stack (e.g., an array of elements) can be accessed only through this user interface. [3] Ensure that the stack is initialized before its first use.
The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.
Section 2.4 Modular Programming 27
C++ provides a mechanism for grouping related data, functions, etc., into separate namespaces. For example, the user interface of a SS t taa c ckk module could be declared and used like this:
nn a amm e ess p paa c cee  S Stt a acc k k { // interface vv o oii d d pp u uss h h(cc h haa r r); cc h haa r r pp o opp (); }
vv o oii d d ff () { SS t taa c ckk :: pp u uss h h(´cc ´); ii f f (SS t taa c ckk :: pp o opp () != ´cc ´) ee r rrr o orr ("ii m mpp o oss s sii b bll e e"); }
The SS t taa c ckk :: qualification indicates that the pp u uss h h() and pp o opp () are those from the SS t taa c ckk name- space. Other uses of those names will not interfere or cause confusion. The definition of the SS t taa c ckk could be provided in a separately-compiled part of the program:
nn a amm e ess p paa c cee  S Stt a acc k k { // implementation cc o onn s stt  i inn t t mm a axx __ ss i izz e e = 22 0 000 ; cc h haa r r vv [mm a axx __ ss i izz e e]; ii n ntt  t too p p = 00 ;
vv o oii d d pp u uss h h(cc h haa r r cc ) { /* check for overflow and push c */ } cc h haa r r pp o opp () { /* check for underflow and pop */ }
}
The key point about this SS t taa c ckk module is that the user code is insulated from the data representation of SS t taa c ckk by the code implementing SS t taa c ckk :: pp u uss h h() and SS t taa c ckk :: pp o opp (). The user doesn’t need to know that the SS t taa c ckk is implemented using an array, and the implementation can be changed without affecting user code. Because data is only one of the things one might want to ‘‘hide,’’ the notion of data hiding is trivially extended to the notion of information hiding; that is, the names of functions, types, etc., can also be made local to a module. Consequently, C++ allows any declaration to be placed in a namespace (§8.2). This SS t taa c ckk module is one way of representing a stack. The following sections use a variety of stacks to illustrate different programming styles.
2.4.1 Separate Compilation [tour.comp]
C++ supports C’s notion of separate compilation. This can be used to organize a program into a set of semi-independent fragments. Typically, we place the declarations that specify the interface to a module in a file with a name indicating its intended use. Thus,
nn a amm e ess p paa c cee  S Stt a acc k k { // interface vv o oii d d pp u uss h h(cc h haa r r); cc h haa r r pp o opp (); }
would be placed in a file ss t taa c ckk .hh , and users will include that file, called a header file, like this:
The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.
28 A Tour of C++ Chapter 2
#ii n ncc l luu d dee "ss t taa c ckk .hh " // get the interface
vv o oii d d ff () { SS t taa c ckk :: pp u uss h h(´cc ´); ii f f (SS t taa c ckk :: pp o opp () != ´cc ´) ee r rrr o orr ("ii m mpp o oss s sii b bll e e"); }
To help the compiler ensure consistency, the file providing the implementation of the SS t taa c ckk module will also include the interface:
#ii n ncc l luu d dee "ss t taa c ckk .hh " // get the interface
nn a amm e ess p paa c cee  S Stt a acc k k { // representation cc o onn s stt  i inn t t mm a axx __ ss i izz e e = 22 0 000 ; cc h haa r r vv [mm a axx __ ss i izz e e]; ii n ntt  t too p p = 00 ; }
vv o oii d d SS t taa c ckk :: pp u uss h h(cc h haa r r cc ) { /* check for overflow and push c */ }
cc h haa r r SS t taa c ckk :: pp o opp () { /* check for underflow and pop */ }
The user code goes in a third file, say uu s see r r.cc . The code in uu s see r r.cc and ss t taa c ckk .cc shares the stack interface information presented in ss t taa c ckk .hh , but the two files are otherwise independent and can be separately compiled. Graphically, the program fragments can be represented like this:
SS t taa c ckk  i inn t tee r rff a acc e e
. . #ii n ncc l luu d dee  " "ss t taa c ckk . .hh " " uu s see  s stt a acc k k
. . #ii n ncc l luu d dee  " "ss t taa c ckk . .hh " " dd e eff i inn e e ss t taa c ckk
. stack.h:
user.c: stack.c:
Separate compilation is an issue in all real programs. It is not simply a concern in programs that present facilities, such as a SS t taa c ckk , as modules. Strictly speaking, using separate compilation isn’t a language issue; it is an issue of how best to take advantage of a particular language implementation. However, it is of great practical importance. The best approach is to maximize modularity, repre- sent that modularity logically through language features, and then exploit the modularity physically through files for effective separate compilation (Chapter 8, Chapter 9).
2.4.2 Exception Handling [tour.except]
When a program is designed as a set of modules, error handling must be considered in light of these modules. Which module is responsible for handling what errors? Often, the module that detects an error doesn’t know what action to take. The recovery action depends on the module that invoked
The C++ Programming Language, Third Edition by Bjarne Stroustrup. Copyright ©1997 by AT&T. Published by Addison Wesley Longman, Inc. ISBN 0-201-88954-4. All rights reserved.
Section 2.4.2 Exception Handling 29
the operation rather than on the module that found the error while trying to perform the operation. As programs grow, and especially when libraries are used extensively, standards for handling errors (or, more generally, ‘‘exceptional circumstances’’) become important. Consider again the SS t taa c ckk example. What ought to be done when we try to pp u uss h h() one too many characters? The writer of the SS t taa c ckk module doesn’t know what the user would like to be done in this case, and the user cannot consistently detect the problem (if the user could, the over- flow wouldn’t happen in the first place). The solution is for the SS t taa c ckk implementer to detect the overflow and then tell the (unknown) user. The user can then take appropriate action. For exam- ple:
nn a amm e ess p paa c cee  S Stt a acc k k { // interface vv o oii d d pp u uss h h(cc h haa r r); cc h haa r r pp o opp ();
cc l laa s sss  O Ovv e err f fll o oww { }; // type representing overflow exceptions
}
When detecting an overflow, SS t taa c ckk :: pp u uss h h() can invoke the exception-handling code; that is, ‘‘throw an OO v vee r rff l loo w w exception:’’
vv o oii d d SS t taa c ckk :: pp u uss h h(cc h haa r r cc ) { ii f f (tt o opp == mm a axx __ ss i izz e e) tt h hrr o oww  O Ovv e err f fll o oww (); // push c }
The tt h hrr o oww transfers control to a handler for exceptions of type SS t taa c ckk :: OO v vee r rff l loo w w in some function that directly or indirectly called SS t taa c ckk :: pp u uss h h(). To do that, the implementation will unwind the function call stack as needed to get back to the context of that caller. Thus, the tt h hrr o oww acts as a mul- tilevel rr e ett u urr n n. For example:
vv o oii d d ff () { // ... tt r ryy { // exceptions here are handled by the handler defined below
ww h hii l lee (tt r ruu e e) SS t taa c ckk :: pp u uss h h(´cc ´);
} cc a att c chh (SS t taa c ckk :: OO v vee r rff l loo w w) { // oops: stack overflow; take appropriate action } // ...
}
The ww h hii l lee loop will try to loop forever. Therefore, the cc a att c chh -clause providing a handler for SS t taa c ckk :: OO v vee r rff l loo w w will be entered after some call of SS t taa c ckk :: pp u uss h h() causes a tt h hrr o oww . Use of the exception-handling mechanisms can make error handling more regular and readable.

I will post the next Chapter soon..

15 comments: