Beginning C++ Programming
eBook - ePub

Beginning C++ Programming

Richard Grimes

  1. 526 pages
  2. English
  3. ePUB (adapté aux mobiles)
  4. Disponible sur iOS et Android
eBook - ePub

Beginning C++ Programming

Richard Grimes

DĂ©tails du livre
Aperçu du livre
Table des matiĂšres

À propos de ce livre

Modern C++ at your fingertips!About This Book‱ This book gets you started with the exciting world of C++ programming‱ It will enable you to write C++ code that uses the standard library, has a level of object orientation, and uses memory in a safe and effective way‱ It forms the basis of programming and covers concepts such as data structures and the core programming languageWho This Book Is ForA computer, an internet connection, and the desire to learn how to code in C++ is all you need to get started with this book.What You Will Learn‱ Get familiar with the structure of C++ projects‱ Identify the main structures in the language: functions and classes‱ Feel confident about being able to identify the execution flow through the code‱ Be aware of the facilities of the standard library‱ Gain insights into the basic concepts of object orientation‱ Know how to debug your programs‱ Get acquainted with the standard C++ libraryIn DetailC++ has come a long way and is now adopted in several contexts. Its key strengths are its software infrastructure and resource-constrained applications, including desktop applications, servers, and performance-critical applications, not to forget its importance in game programming. Despite its strengths in these areas, beginners usually tend to shy away from learning the language because of its steep learning curve.The main mission of this book is to make you familiar and comfortable with C++. You will finish the book not only being able to write your own code, but more importantly, you will be able to read other projects. It is only by being able to read others' code that you will progress from a beginner to an advanced programmer. This book is the first step in that progression.The first task is to familiarize you with the structure of C++ projects so you will know how to start reading a project. Next, you will be able to identify the main structures in the language, functions, and classes, and feel confident being able to identify the execution flow through the code. You will then become aware of the facilities of the standard library and be able to determine whether you need to write a routine yourself, or use an existing routine in the standard library.Throughout the book, there is a big emphasis on memory and pointers. You will understand memory usage, allocation, and access, and be able to write code that does not leak memory. Finally, you will learn about C++ classes and get an introduction to object orientation and polymorphism.Style and approachThis straightforward tutorial will help you build strong skills in C++ programming, be it for enterprise software or for low-latency applications such as games or embedded programming. Filled with examples, this book will take you gradually up the steep learning curve of C++.

Foire aux questions

Comment puis-je résilier mon abonnement ?
Il vous suffit de vous rendre dans la section compte dans paramĂštres et de cliquer sur « RĂ©silier l’abonnement ». C’est aussi simple que cela ! Une fois que vous aurez rĂ©siliĂ© votre abonnement, il restera actif pour le reste de la pĂ©riode pour laquelle vous avez payĂ©. DĂ©couvrez-en plus ici.
Puis-je / comment puis-je télécharger des livres ?
Pour le moment, tous nos livres en format ePub adaptĂ©s aux mobiles peuvent ĂȘtre tĂ©lĂ©chargĂ©s via l’application. La plupart de nos PDF sont Ă©galement disponibles en tĂ©lĂ©chargement et les autres seront tĂ©lĂ©chargeables trĂšs prochainement. DĂ©couvrez-en plus ici.
Quelle est la différence entre les formules tarifaires ?
Les deux abonnements vous donnent un accĂšs complet Ă  la bibliothĂšque et Ă  toutes les fonctionnalitĂ©s de Perlego. Les seules diffĂ©rences sont les tarifs ainsi que la pĂ©riode d’abonnement : avec l’abonnement annuel, vous Ă©conomiserez environ 30 % par rapport Ă  12 mois d’abonnement mensuel.
Qu’est-ce que Perlego ?
Nous sommes un service d’abonnement Ă  des ouvrages universitaires en ligne, oĂč vous pouvez accĂ©der Ă  toute une bibliothĂšque pour un prix infĂ©rieur Ă  celui d’un seul livre par mois. Avec plus d’un million de livres sur plus de 1 000 sujets, nous avons ce qu’il vous faut ! DĂ©couvrez-en plus ici.
Prenez-vous en charge la synthÚse vocale ?
Recherchez le symbole Écouter sur votre prochain livre pour voir si vous pouvez l’écouter. L’outil Écouter lit le texte Ă  haute voix pour vous, en surlignant le passage qui est en cours de lecture. Vous pouvez le mettre sur pause, l’accĂ©lĂ©rer ou le ralentir. DĂ©couvrez-en plus ici.
Est-ce que Beginning C++ Programming est un PDF/ePUB en ligne ?
Oui, vous pouvez accĂ©der Ă  Beginning C++ Programming par Richard Grimes en format PDF et/ou ePUB ainsi qu’à d’autres livres populaires dans Computer Science et Programming in C++. Nous disposons de plus d’un million d’ouvrages Ă  dĂ©couvrir dans notre catalogue.



Exploring C++ Types

In the last two chapters, you have learned how to put together a C++ program, learned about the files you use, and the ways to control execution flow. This chapter is about the data that you will use in your program: the type of data and the variables that will hold that data.
A variable can handle data of a particular format and with a particular behavior, and that is determined by the type of the variable. The type of the variable determines the operations you can perform on the data and on the format of the data when inputted or viewed by the user.
Essentially, you can view three general categories of types: built-in types, custom types, and pointers. Pointers in general will be covered in the next chapter, and custom types, or classes, and pointers to them, will be covered in Chapter 6, Classes. This chapter will cover the types that are provided as part of the C++ language.

Exploring built-in types

C++ provides integer, floating point, and Boolean types. The char type is an integer but it can be used to hold individual characters and so its data can be viewed as a number or as a character. The C++ Standard Library provides the string class to allow you to use and manipulate strings of characters. Strings will be covered in depth in Chapter 9, Using Strings.
As the name suggests, integer types contain integral values where there are no fractional parts. If you perform calculations with integers you should expect that any fractional parts will be discarded unless you take steps to retain them (for example, through the remainder operator %). Floating point types hold numbers that may have a fractional part; because floating point types can hold numbers in a mantissa exponent format, they can hold exceptionally large or exceptionally small numbers.
A variable is an instance of a type; it is the memory allocated to hold the data that the type can hold. Integer and floating point variable declarations can be modified to tell the compiler how much memory to allocate, and thus the limits of the data that the variable can hold and the precision of the calculations performed on the variable. In addition, you can also indicate if the variable will hold a number where the sign is important. If the number is being used to hold bitmaps (where the bits do not make up a number, but have a separate meaning of their own) then it usually makes no sense to use a signed type.
In some cases, you will be using C++ to unpack data from a file or a network stream so that you can manipulate it. In this case, you will need to know whether the data is a floating point or integral, signed or unsigned, how many bytes are used and what order those bytes will be in. The order of the bytes (whether the first byte in a multi-byte number is the low or high part of the number) is determined by the processor which you are compiling for, and in most cases, you will not need to worry about it.
Similarly, sometimes you may need to know about the size of a variable and how it is aligned in memory; in particular, when you are using records of data, known in C++ as structs. C++ provides the sizeof operator to give the number of bytes used to hold a variable and the alignof operator to determine the alignment of the type in memory. For basic types, the sizeof and alignof operators return the same value; it is only necessary to call the alignof operator on custom types where it will return the alignment of the largest data member in the type.


As the name suggests, an integer holds integral data, numbers that have no fractional part. For this reason, it makes little sense to do any arithmetic with an integer where the fractional part is important; in this case, you should use floating point numbers. An example of this was shown in the last chapter:
 int height = 480; 
int width = 640;
int aspect_ratio = width / height;
This gives an aspect ratio of 1, which is clearly untrue and serves no purpose. Even if you assign the result to a floating-point number, you will get the same result:
 float aspect_ratio = width / height;
The reason is that the arithmetic is performed in the expression width / height, which will use the division operator for integers that will throw away any fractional part of the result. To use the floating-point division operator you will have to cast one or other of the operands to a floating-point number so the floating-point operator is used:
 float aspect_ratio = width / (float)height;
This will assign a value of 1.3333 (or 4 : 3) to the aspect_ratio variable. The cast operator used here is the C cast operator, which forces data of one type to be used as data of another type. (It is used because we have not yet introduced the C++ cast operators, and the syntax of C cast operators is clear.) There is no type safety in this cast. C++ provides cast operators, which are discussed in the following text, some of which will cast in a type-safe way, which becomes important when you use pointers to objects of custom types.
C++ provides integer types of various sizes, as summarized in the following table. These are the five standard integer types. The standard says that an int is the natural size of the processor and will have a value between (and including) INT_MIN and INT_MAX (defined in the <climits> header file). The size of the integer type has at least as much storage as those preceding it in the list, so an int is, at least, as big as a short int and a long long int types, which is at least as big as a long int type. The phrase at least as big as is not much use if the types are all the same size, so the <climits> header file defines ranges for the other fundamental integer types too. It is implementation-specific how many bytes are needed to store these integer ranges. This table gives the ranges of the fundamental types and the sizes on x86, 32-bit processors:
Type Range Size in bytes
signed char -128 to 127 1
short int -32768 to 32767 2
int -2147483648 to 2147483647 4
long int -2147483648 to 2147483647 4
long long int -9223372036854775808 to 9223372036854775807 8
In practice, rather than the short int type, you will use short; for long int, you will use long; and for long long int, you will typically use long long. As you can see from this table, the int and long int types are the same size, but they are still two different types.
Other than the char type, by default integer types are signed, that is, they can hold negative as well as positive numbers (for example, a variable of type short can have a value between -32,768 and 32,767). You can use the signed keyword to explicitly indicate that the type is signed. You can also have unsigned equivalents by using the unsigned keyword, which will give you an extra bit, but will also mean that bitwise operators and shift operators will work as you expect. You may find unsigned used without a type, in which case it refers to unsigned int. Similarly, signed used without a type refers to signed int.
The char type is a separate type to both unsigned char and signed char. The standard says that every bit in a char is used to hold character information, and so it is implementation-dependent as to whether a char can be treated as being able to hold negative numbers. If you want a char to hold a signed number, you should specifically use signed char.
The standard is imprecise about the size of the standard integer types and this may be an issue if you are writing code (for example, accessing data in a file, or a network stream) that contains a stream of bytes. The <cstdlib> header file defines named types that will hold specific ranges of data. These types have names which have the number of bits used in the range (although the actual type may require more bits). So, there are types with names such as int16_t and uint16_t, where the first type is a signed integer that will hold a range of 16-bit values and the second type is an unsigned integer. There are also types declared for 8-, 32-, and 64-bit values.
The following shows the actual sizes of these types determined by the sizeof operator on an x86 machine:
 // #include <cstdint> 
using namespace std; // Values for x86
cout << sizeof(int8_t) << endl; // 1
cout << sizeof(int16_t) << endl; // 2
cout << sizeof(int32_t) << endl; // 4
cout << sizeof(int64_t) << endl; // 8
In addition, the <cstdlib> header file defines types with names such as int_least16_t and uint_least16_t using the same naming scheme as before, and with versions for 8-, 16-,32-, and 64-bits. The least part of the name means that the type will hold values with at least the specified number of bits, but there could be more. There are also types with names such as int_fast16_t and uint_fast16_t with versions for 8-, 16-, 32-, and 64-bits which are regarded as the fastest types that can hold that number of bits.

Specifying integer literals

To assign a value to an integer variable you provide a number that has no fractional part. The compiler will identify the type with the ne...

Table des matiĂšres

  1. Title Page
  2. Copyright
  3. Credits
  4. About the Author
  5. About the Reviewer
  7. Customer Feedback
  8. Preface
  9. Starting with C++
  10. Understanding Language Features
  11. Exploring C++ Types
  12. Working with Memory, Arrays, and Pointers
  13. Using Functions
  14. Classes
  15. Introduction to Object-Orientated Programming
  16. Using the Standard Library Containers
  17. Using Strings
  18. Diagnostics and Debugging