text:
C++ Programming/Operators/Arrays

Arrays
An array stores a constant-sized sequential set of blocks, each block containing a value of the selected type under a single name. Arrays often help organize collections of data efficiently and intuitively.

It is easiest to think of an array as simply a list with each value as an item of the list. Where individual elements are accessed by their position in the array called its index, also known as subscript. Each item in the array has an index from 0 to (the size of the array) -1, indicating its position in the array.

Advantages of arrays include:
 * Random access in O(1) (Big O notation)
 * Ease of use/port: Integrated into most modern languages

Disadvantages include:
 * Constant size
 * Constant data-type
 * Large free sequential block to accommodate large arrays
 * When used as non-static data members, the element type must allow default construction
 * Arrays do not support copy assignment (you cannot write )
 * Arrays cannot be used as the value type of a standard container
 * Syntax of use differs from standard containers
 * Arrays and inheritance don't mix (an array of Derived is not an array of Base, but can too easily be treated like one)

For example, here is an array of integers, called List with 5 elements, numbered 0 to 4. Each element of the array is an integer. Like other integer variables, the elements of the array start out uninitialized. That means it is filled with unknown values until we initialize it by assigning something to it. (Remember primitive types in C are not initialized to 0.)

Since an array stores values, what type of values and how many values to store must be defined as part of an array declaration, so it can allocate the needed space. The size of array must be a const integral expression greater than zero. That means that you cannot use user input to declare an array. You need to allocate the memory (with operator new[]), so the size of an array has to be known at compile time. Another disadvantage of the sequential storage method is that there has to be a free sequential block large enough to hold the array. If you have an array of 500,000,000 blocks, each 1 byte long, you need to have roughly 500 megabytes of sequential space to be free; Sometimes this will require a defragmentation of the memory, which takes a long time.

To declare an array you can do:

or

and so on...

to initialize as you declare them you can use:

this will not only create the array with 6 int elements but also initialize them to the given values.

If you initialize the array with less than the full number of elements, the remaining elements are set to a default value - zero in the case of numbers.

If you fully initialize the array as you declare it, you can allow the compiler to work out the size of the array:

Assigning and accessing data
You can assign data to the array by using the name of the array, followed by the index.

For example to assign the number 200 into the element at index 2 in the array

will give

You can access the data at an element of the array the same way.

This will print 200.

Basically working with individual elements in an array is no different then working with normal variables.

As you see accessing a value stored in an array is easy. Take this other example:

The above declaration will assign x the valued store at index 2 of variable vector which is 1.

Arrays are indexed starting at 0, as opposed to starting at 1. The first element of the array above is vector[0]. The index to the last value in the array is the array size minus one. In the example above the subscripts run from 0 through 5. C++ does not do bounds checking on array accesses. The compiler will not complain about the following:

During program execution, an out of bounds array access does not always cause a run time error. Your program may happily continue after retrieving a value from vector[-1]. To alleviate indexing problems, the expression is commonly used when coding loops that process arrays.

Notice in the above example, the size of the array was not explicitly specified. The compiler knows to size it at 5 because of the five values in the initializer list. Adding an additional value to the list will cause it to be sized to six, and because of the expression in the  loop, the code automatically adjusts to this change.

multidimensional arrays
You can also use multi-dimensional arrays. The simplest type is a two dimensional array. This creates a rectangular array - each row has the same number of columns. To get a char array with 3 rows and 5 columns we write...

To access/modify a value in this array we need two subscripts:

or

example
There are also weird notations possible:

a[i] and i[a] point to the same location. You will understand this better after knowing about pointers.

To get an <tt>array</tt> of a different size, you must explicitly deal with memory using <tt>realloc</tt>, <tt>malloc</tt>, <tt>memcpy</tt>, etc.

Why start at 0?
Most programming languages number arrays from 0. This is useful in languages where arrays are used interchangeably with a pointer to the first element of the array. In C++ the address of an element in the array can be computed from (address of first element) + i, where i is the index starting at 0 (a[1] == *(a + 1)). Notice here that "(address of the first element) + i" is not a literal addition of numbers. Different types of data have different sizes and the compiler will correctly take this into account. Therefore, it is simpler for the pointer arithmetic if the index started at 0.

Why no bounds checking on array indexes?
C++ does allow for, but doesn't force, bounds-checking implementations, in practice little or no checking is done. It affects storage requirements (needing "fat pointers") and impacts runtime performance. However, the <tt>std::vector</tt> template class, that we mentioned and we will examine later in greater detail (a template class container, representing an array provides the <tt>at</tt> method) which does enforce bounds checking. Also in many implementations, the standard containers include particularly complete bounds checking in debug mode. They might not support these checks in release builds, as any performance reduction in container classes relative to built-in arrays might prevent programmers from migrating from arrays to the more modern, safer container classes.

title: C++ Programming/Operators/Arrays


text:
C++ Programming/Booklinks

Introductory books

 * Thinking in C++, 2nd ed. Volume 1: Introduction to Standard C++ by Bruce Eckel, ISBN 0139798099 | ISBN 978-0139798092. Available online and also as.

Advanced topics

 * Thinking in C++, 2nd ed. Volume 2: Practical Programming by Bruce Eckel, 0139798099 | ISBN 978-0139798092. Available online as.
 * Effective C++ : 55 Specific Ways to Improve Your Programs and Designs, 3rd ed. by Scott Meyers, ISBN 0321334876

Reference books

 * C++ in a Nutshell by Ray Lischner, ISBN 059600298X

 * C++ Pocket Reference by Kyle Loudon, ISBN 0596004966

 * C++ FAQs by Marshall Cline, Greg Lomow, and Mike Girou, Addison-Wesley, 1999, ISBN 0-201-30983-1

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

title: C++ Programming/Booklinks


text:
C++ Programming/Libraries/Boost

The Boost project (http://www.boost.org/) provides free peer-reviewed, open source libraries that extend the functionality of C++. Most of the libraries are licensed under the Boost Software License, designed to allow Boost to be used with both open and closed source projects.

Many of Boost's founders are on the C++ standard committee and several Boost libraries have been accepted for incorporation into the Technical Report 1 of C++0x. Although Boost was begun by members of the C++ Standards Committee Library Working Group, participation has expanded to include thousands of programmers from the C++ community at large.

The emphasis is on libraries which work well with the C++ Standard Library. The libraries are aimed at a wide range of C++ users and application domains, and are in regular use by thousands of programmers. They range from general-purpose libraries like SmartPtr, to OS Abstractions like FileSystem, to libraries primarily aimed at other library developers and advanced C++ users, like MPL.

A further goal is to establish "existing practice" and provide reference implementations so that Boost libraries are suitable for eventual standardization. Ten Boost libraries will be included in the C++ Standards Committee's upcoming  C++ Standard Library Technical Report as a step toward becoming part of a future C++ Standard.

In order to ensure efficiency and flexibility, Boost makes extensive use of templates. Boost has been a source of extensive work and research into generic programming and metaprogramming in C++.

Libraries
Libraries by category
 * Concurrent programming
 * ... TODO

 * Algorithms
 * Concurrent programming (threads)
 * Containers
 * array - Management of fixed-size arrays with STL container semantics
 * Boost Graph Library (BGL) - Generic graph containers, components and algorithms
 * multi-array - Simplifies creation of N-dimensional arrays
 * multi-index containers - Containers with built in indexes that allow different sorting and access semantics
 * pointer containers - Containers modeled after most standard STL containers that allow for transparent management of pointers to values
 * property map - Interface specifications in the form of concepts and a general purpose interface for mapping key values to objects
 * variant - A safe and generic stack-based object container that allows for the efficient storage of and access to an object of a type that can be chosen from among a set of types that must be specified at compile time.
 * Correctness and testing
 * concept check - Allows for the enforcement of actual template parameter requirements (concepts)
 * static assert - Compile time assertion support
 * Boost Test Library - A matched set of components for writing test programs, organizing tests into test cases and test suites, and controlling their runtime execution
 * Data structures
 * dynamic_bitset - Dynamic like data structure
 * Function objects and higher-order programming
 * bind and mem_fn - General binders for functions, function objects, function pointers and member functions
 * function - Function object wrappers for deferred calls. Also, provides a generalized mechanism for callbacks
 * functional - Enhancements to the function object adapters specified in the C++ Standard Library, including:
 * function object traits
 * negators
 * binders
 * adapters for pointers to functions
 * adapters for pointers to member functions
 * hash - An implementation of the hash function object specified by the C++ Technical Report 1 (TR1). Can be used as the default hash function for unordered associative containers
 * lambda - In the spirit of lambda abstractions, allows for the definition of small anonymous function objects and operations on those objects at a call site, using placeholders, especially for use with deferred callbacks from algorithms.
 * ref - Provides utility class templates for enhancing the capabilities of standard C++ references, especially for use with generic functions
 * result_of - Helps in the determination of the type of a call expression
 * Signals2 - Managed signals and slots callback implementation
 * Generic programming
 * Graphs
 * Input/output
 * Interlanguage support (for Python)
 * Iterators
 * iterators
 * operators - Class templates that help with overloaded operator definitions for user defined iterators and classes that can participate in arithmetic computation.
 * tokenizer - Provides a view of a set of tokens contained in a sequence that makes them appear as a container with iterator access
 * Math and Numerics
 * Memory
 * pool - Provides a simple segregated storage based memory management scheme
 * smart_ptr - A collection of smart pointer class templates with different pointee management semantics
 * scoped_ptr - Owns the pointee (single object)
 * scoped_array - Like scoped_ptr, but for arrays
 * shared_ptr - Potentially shares the pointer with other shared_ptrs. Pointee is destroyed when last shared_ptr to it is destroyed
 * shared_array - Like shared_ptr, but for arrays
 * weak_ptr - Provides a "weak" reference to an object that is already managed by a shared_ptr
 * intrusive_ptr - Similared to shared_ptr, but uses a reference count provided by the pointee
 * utility - Miscellaneous support classes, including:
 * base from member idiom - Provides a workaround for a class that needs to initialize a member of a base class inside its own (i.e., the derived class') constructor's initializer list
 * checked delete - Check if an attempt is made to destroy an object or array of objects using a pointer to an incomplete type
 * next and prior functions - Allow for easier motion of a forward or bidirectional iterator, especially when the results of such a motion need to be stored in a separate iterator (i.e., should not change the original iterator)
 * noncopyable - Allows for the prohibition of copy construction and copy assignment
 * addressof - Allows for the acquisition of an object's real address, bypassing any overloads of operator&, in the process
 * result_of - Helps in the determination of the type of a call expression
 * Miscellaneous
 * Parsers
 * Preprocessor metaprogramming
 * String and text processing
 * lexical_cast - Type conversions to/from text
 * format - Type safe argument formatting according to a format string
 * iostreams - C++ streams and stream buffer assistance for new sources/sinks, filters framework
 * regex - Support for regular expressions
 * Spirit - An object-oriented recursive-descent parser generator framework
 * string algorithms - A collection of various algorithms related to strings
 * tokenizer - Allows for the partitioning of a string or other character sequence into tokens
 * wave - Standards conformant implementation of the mandated C99 / C++ pre-processor functionality packed behind an easy to use interface
 * Template metaprogramming
 * mpl - A general purpose high-level metaprogramming framework of compile-time algorithms, sequences and metafunctions
 * static assert - Compile time assertion support
 * type traits - Templates that define the fundamental properties of types
 * Workarounds for broken compilers

The current Boost release contains 87 individual libraries, including the following three:

noncopyable
The boost::noncopyable utility class that ensures that objects of a class are never copied.

Linear algebra – uBLAS
Boost includes the uBLAS linear algebra library (faster alternative libraries include armadillo and eigen), with BLAS support for vectors and matrices. uBlas supports a wide range of linear algebra operations, and has bindings to some widely used numerics libraries, such as ATLAS, BLAS and LAPACK.

 * Example showing how to multiply a vector with a matrix:

Generating random numbers – Boost.Random
Boost provides distribution-independent pseudorandom number generators and PRNG-independent probability distributions, which are combined to build a concrete generator. See Boost Random Number Library for more details.
 * Example showing how to sample from a normal distribution using the Mersenne Twister generator:

Multi-threading – Boost.Thread
Example code that demonstrates creation of threads:

See also Threading with Boost - Part I: Creating Threads

Thread locking
Example usage of a mutex to enforce exclusive access to a function:

Example of read/write locking of a property:

 * Introduction to Boost.Threads in Dr. Dobb's Journal. (2002)
 * What's New in Boost Threads? in Dr. Dobb's Journal. (2008)
 * Boost.Threads API reference.
 * threadpool library based on Boost.Thread
 * Ceemple Boost included in Ceemple, a rapid JIT based C++ technical computing environment.

title: C++ Programming/Libraries/Boost


text:
C++ Programming/Classes

Classes
Classes are used to create user defined types. An instance of a class is called an object and programs can contain any number of classes. As with other types, object types are case-sensitive.

Classes provide encapsulation as defined in the Object Oriented Programming (OOP) paradigm. A class can have both data members and functions members associated with it. Unlike the built-in types, the class can contain several variables and functions, those are called members.

Classes also provide flexibility in the "divide and conquer" scheme in program writing. In other words, one programmer can write a class and guarantee an interface. Another programmer can write the main program with that expected interface. The two pieces are put together and compiled for usage.

Declaration
A class is defined by:

An object of type MyClass (case-sensitive) is declared using:

 * by default, all class members are initially private.
 * keywords public and protected allow access to class members.
 * classes contain not only data members, but also functions to manipulate that data.
 * a class is used as the basic building block of OOP (this is a distinction of convention, not of language-enforced semantics).

 * A class can be created
 * before main is called.
 * when a function is called in which the object is declared.
 * when the "new" operator is used.

 * Class Names
 * Name the class after what it is. If you can't determine a name, then you have not designed the system well enough.
 * Compound names of over three words are a clue your design may be confusing various entities in your system. Revisit your design. Try a CRC card session to see if your objects have more responsibilities than they should.
 * Avoid the temptation of naming a class something similar to the class it is derived from. A class should stand on its own. Declaring an object with a class type doesn't depend on where that class is derived from.
 * Suffixes or prefixes are sometimes helpful. For example, if your system uses agents then naming something DownloadAgent conveys real information.

A fundamental concept of Object Oriented (OO) recommends an object should not expose any of its implementation details. This way, you can change the implementation without changing the code that uses the object. The class, by design, allows its programmer to hide (and also prevents changes as to) how the class is implemented. This powerful tool allows the programmer to build in a 'preventive' measure. Variables within the class often have a very significant role in what the class does, therefore variables can be secured within the private section of the class.
 * Data Abstraction

Access labels
The access labels Public, Protected and Private are used within classes to set access permissions for the members in that section of the class. All class members are initially private by default. The labels can be in any order. These labels can be used multiple times in a class declaration for cases where it is logical to have multiple groups of these types. An access label will remain active until another access label is used to change the permissions.

We have already mentioned that a class can have member functions "inside" it; we will see more about them later. Those member functions can access and modify all the data and member function that are inside the class. Therefore, permission labels are to restrict access to member function that reside outside the class and for other classes.

For example, a class "Bottle" could have a private variable fill, indicating a liquid level 0-3 dl. fill cannot be modified directly (compiler error), but instead Bottle provides the member function sip to reduce the liquid level by 1. Mywaterbottle could be an instance of that class, an object.

These keywords, private, public, and protected, affect the permissions of the members—whether functions or variables.

public
This label indicates any members within the 'public' section can be accessed freely anywhere a declared object is in scope.

private
Members defined as private are only accessible within the class defining them, or friend classes. Usually the domain of member variables and helper functions. It's often useful to begin putting functions here and then moving them to the higher access levels as needed so to reduce complexity.

(This is an example where the default copy constructor will do the same thing.)

protected
The protected label has a special meaning to inheritance, protected members are accessible in the class that defines them and in classes that inherit from that base class, or friends of it. In the section on inheritance we will see more about it.

Data members
Data members are declared in the same way as a global or function variable, but as part of the class definition. Their purpose is to store information for that class and may include members of any type, even other user-defined types. They are usually hidden from outside use, depending on the coding style adopted, external use is normally done through special member functions.

Subsumption property
Subsumption is a property that all objects that reside in a class hierarchy must fulfill: an object of the base class can be substituted by an object that derives from it (directly or indirectly). All mammals are animals (they derive from them), and all cats are mammals. Therefore, because of the subsumption property we can "treat" any mammal as an animal and any cat as a mammal. This implies abstraction, because when we are "treating" a mammal as an animal, the only information we should know about it is that it lives, it grows, etc, but nothing related to mammals.

This property is applied in C++, whenever we are using pointers or references to objects that reside in a class hierarchy. In other words, a pointer of class animal can point to an object of class animal, mammal or cat.

Let's continue with our example:

In the last lines of the example there is cast of a pointer to Animal, to a pointer to Cat. This is called "Downcast". Downcasts are useful and should be used, but first we must ensure that the object we are casting is really of the type we are casting to it. Downcasting a base class to an unrelated class is an error. To resolve this issue, the casting operators <>, or <> should be used. These correctly cast an object from one class to another, and will throw an exception if the class types are not related. eg. If you try:

Then, the app will throw an exception, as a cat is not a motorbike. Static_cast is very similar, only it will perform the type checking at compile time. If you have an object where you are not sure of its type then you should use, and be prepared to handle errors when casting. If you are downcasting objects where you know the types, then you should use. Do not use old-style C casts as these will simply give you an access violation if the types cast are unrelated.

Local classes
A local class is any class that is defined inside a specific statement block, in a local scope, for instance inside a function. This is done like defining any other class, but local classes can not however access non-static local variables or be used to define static data members. These type of classes are useful especially in template functions, as we will see later.

User defined automatic type conversion
We already covered automatic type conversions (implicit conversion) and mentioned that some can be user-defined.

A user-defined conversion from a class to another class can be done by providing a constructor in the target class that takes the source class as an argument,  or by providing the target class with a conversion operator, as.

Ensuring objects of a class are never copied
This is required e.g. to prevent memory-related problems that would result in case the default copy-constructor or the default assignment operator is unintentionally applied to a class C which uses dynamically allocated memory, where a copy-constructor and an assignment operator are probably an overkill as they won't be used frequently.

Some style guidelines suggest making all classes non-copyable by default, and only enabling copying if it makes sense. Other (bad) guidelines say that you should always explicitly write the copy constructor and copy assignment operators; that's actually a bad idea, as it adds to the maintenance effort, adds to the work to read a class, is more likely to introduce errors than using the implicitly declared ones, and doesn't make sense for most object types. A sensible guideline is to think about whether copying makes sense for a type; if it does, then first prefer to arrange that the compiler-generated copy operations will do the right thing (e.g., by holding all resources via resource management classes rather than via raw pointers or handles), and if that's not reasonable then obey the law of three. If copying doesn't make sense, you can disallow it in either of two idiomatic ways as shown below.

Just declare the copy-constructor and assignment operator, and make them private. Do not define them. As they are not protected or public, they are inaccessible outside the class. Using them within the class would give a linker error since they are not defined.

Remember that if the class uses dynamically allocated memory for data members, you must define the memory release procedures in destructor ~C  to release the allocated memory.

A class which only declares these two functions can be used as a private base class, so that all classes which privately inherits such a class will disallow copying.

Container class
A class that is used to hold objects in memory or external storage is often called a container class. A container class acts as a generic holder and has a predefined behavior and a well-known interface. It is also a supporting class whose purpose is to hide the topology used for maintaining the list of objects in memory. When it contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the container is called a homogeneous container.

Singleton class
A Singleton class is a class that can only be instantiated once (similar to the use of static variables or functions). It is one of the possible implementations of a creational pattern, which is fully covered in the Design Patterns Section of the book.

de:C++-Programmierung: Klassen Programación en C++/Objetos y Clases Programmation C++/Les classes C++/Czym jest obiekt Programar em C++/Classes

title: C++ Programming/Classes


text:
C++ Programming/Examples/Using A Class

|6

title: C++ Programming/Examples/Using A Class


text:
C++ Programming/Classes/Nice Class

What is a "nice" (container safe) class?
A "nice" class takes into consideration the use of the following functions:

1. The copy constructor. 2. The assignment operator. 3. The equality operator. 4. The inequality operator.

Description
A "nice" class could also be called a container safe class. Many containers such as those in the Standard Template Library (STL), that we'll see later, use copy construction and the assignment operator when interacting with the objects of your class. The assignment operator and copy constructor only need to be declared and defined if the default behavior, which is a member-wise (not binary) copy, is undesirable or insufficient to properly copy/construct your object.

A general rule of thumb is that if the default, member-wise copy operations do not work for your objects then you should define a suitable copy constructor and assignment operator. They are both needed if either is defined.

Copy Constructor
The purpose of the copy constructor is to allow the programmer to perform the same instructions as the assignment operator with the special case of knowing that the caller is initializing/constructing rather than an copying.

It is also good practice to use the explicit keyword when using a copy constructor to prevent unintended implicit type conversion.

Example

Equality Operator
The equality operator says, "Is this object equal to that object?". What constitutes equal is up to the programmer. This is a requirement if you ever want to use the equality operator with objects of your class.

However, in most applications (e.g. mathematics), it is usually the case that coding the inequality is easier than coding the equality. In which case the following code can be written for the equality.

Inequality Operator
The inequality operator says, "Is this object not equal to that object?". What constitutes not equal is up to the programmer. This is a requirement if you ever want to use the inequality operator with objects of your class.

However, in some applications, coding the equality is easier than coding the inequality. In which case the following code can be written for the inequality.

If the statement about the (in)equality operators having different efficiency (whatever kind) seems complete nonsense to you, consider that typically, all object attributes must match for two objects to be considered equal. Typically, only one object attribute must differ for two objects to be considered unequal. For equality and inequality operators, that doesn't mean one is faster than the other.

Note, however, that using both the above equality and inequality functions as defined will result in an infinite recursive loop and care must be taken to use only one or the other. Also, there are some situations where neither applies and therefore neither of the above can be used.

Given two objects A and B (with class attributes x and y), an equality operator could be written as

while an inequality operator could be written as

So yes, the equality operator can certainly be written ...!(a!=b)..., but it isn't any faster. In fact, there's the additional overhead of a method call and a negation operation.

So the question becomes, is a little execution overhead worth the smaller code and improved maintainability? There is no simple answer to this it all depend on how the programmer is using them. If your class is composed of, say, an array of 1 billion elements, the overhead is negligible.

title: C++ Programming/Classes/Nice Class


text:
C++ Programming/Programming Languages/C++/Code/Style Conventions

Coding style conventions
The use of a guide or set of convention gives programmers a set of rules for code normalization or coding style that establishes how to format code, name variables, place comments or any other non language dependent structural decision that is used on the code. This is very important, as you share a project with others. Agreeing to a common set of coding standards and recommendations saves time and effort, by enabling a greater understanding and transparency of the code base, providing a common ground for undocumented structures, making for easy debugging, and increasing code maintainability. These rules may also be referred to as Source Code Style, Code Conventions, Coding Standards or a variation of those.

Many organizations have published C++ style guidelines. A list of different approaches can be found on the C++ coding conventions Reference Section. The most commonly used style in C++ programming is ANSI or Allman while much C programming is still done in the Kernighan and Ritchie (K&R) style. You should be warned that this should be one of the first decisions you make on a project and in a democratic environment, a consensus can be very hard to achieve.

Video of the presentation of Bjarne Stroustrup about Style Conventions (not only C++14) https://github.com/isocpp/CppCoreGuidelines and link to the guidelines: https://github.com/isocpp/CppCoreGuidelines|CppCoreGuidelines Video of the presentation of Herb Sutter about Style Conventions (not only C++14) https://www.youtube.com/watch?v=hEx5DNLWGgA link for GSL (Guidelines Support Library) https://github.com/Microsoft/GSL

Programmers tend to stick to a coding style, they have it automated and any deviation can be very hard to conform with, if you don't have a favorite style try to use the smallest possible variation to a common one or get as broad a view as you can get, permitting you to adapt easily to changes or defend your approach. There is software that can help to format or beautify the code, but automation can have its drawbacks. As seen earlier, indentation and the use of white spaces or tabs are completely ignored by the compiler. A coding style should vary depending on the lowest common denominator of the needs to standardize.

Another factor, even if yet to a minimal degree, for the selection of a coding style convention is the IDE (or the code editor) and its capabilities, this can have for instance an influence in determining how verbose code should be, the maximum length of lines, etc. Some editors now have extremely useful features like word completion, refactoring functionalities and other that can make some specifications unnecessary or outright outdated. This will make the adoption of a coding style dependent also on the target code user available software.

Field impacted by the selection of a Code Style are:
 * Re-usability
 * Self documenting code
 * Internationalization
 * Maintainability
 * Portability
 * Optimization
 * Build process
 * Error avoidance
 * Security

No matter which particular coding style you pick, once it is selected, it should be kept throughout the same project. Reading code that follows different styles can become very difficult. In the next sections we try to explain why some of the options are common practice without forcing you to adopt a specific style.
 * Standardization is important

25 lines 80 columns
This rule is a commonly recommended, but often countered with argument that the rule is outdated. The rule originates from the time when text-based computer terminals and dot-matrix printers often could display at most 80 columns of text. As such, greater than 80-column text would either inconveniently wrap to the next line, or worse, not display at all.

The physical limitations of the devices asides, this rule often still suggested under the argument that if you are writing code that will go further than 80 columns or 25 lines, it's time to think about splitting the code into functions. Smaller chunks of encapsulated code helps in reviewing the code as it can be seen all at once without scrolling up or down. This modularizes, and thus eases, the programmer mental representation of the project. This practice will save you precious time when you have to return to a project you haven't been working on for 6 months.

For example, you may want to split long output statements across multiple lines:

This recommended practice relates also to the 0 means success convention for functions, that we will cover on the Functions Section of this book.

Whitespace and indentation
Conventions followed when using whitespace to improve the readability of code is called an indentation style. Every block of code and every definition should follow a consistent indention style. This usually means everything within  and. However, the same thing goes for one-line code blocks.

Use a fixed number of spaces for indentation. Recommendations vary; 2, 3, 4, 8 are all common numbers. If you use tabs for indention you have to be aware that editors and printers may deal with, and expand, tabs differently. The K&R standard recommends an indentation size of 4 spaces.

The use of tab is controversial, the basic premise is that it reduces source code portability, since the same source code loaded into different editors with distinct setting will not look alike. This is one of the primary reasons why some programmers prefer the consistency of using spaces (or configure the editor to replace the use of the tab key with the necessary number of spaces).

For example, a program could as well be written using as follows: However, the same code could be made much more readable with proper indentation:

Placement of braces (curly brackets)
As we have seen early on the Statements Section, compound statements are very important in C++, they also are subject of different coding styles, that recommend different placements of opening and closing braces ( and  ). Some recommend putting the opening brace on the line with the statement, at the end (K&R). Others recommend putting these on a line by itself, but not indented (ANSI C++). GNU recommends putting braces on a line by itself, and indenting them half-way. We recommend picking one brace-placement style and sticking with it.

Examples:

Explicitness or implicitness
This can be defended both ways. If defaulting to implicitness, this means less typing but also may create wrong assumptions on the human reader and for the compiler (depending on the situation) to do extra work, on the other hand if you write more keywords and are explicit on your intentions the resulting code will be clearer and reduces errors (enabling hidden errors to be found), or more defined (self documented) but this may also lead to added limitations to the code's evolution (like we will see with the use of const). This is a thin line where an equilibrium must be reached in accord to the projects nature, and the available capabilities of the editor, code completion, syntax coloring and hovering tooltips reduces much of the work. The important fact is to be consistent as with any other rule.

The choice of using of even if the member function is implicitly inlined.

const
Unless you plan on modifying it, you're arguably better off using const data types. The compiler can easily optimize more with this restriction, and you're unlikely to accidentally corrupt the data. Ensure that your methods take const data types unless you absolutely have to modify the parameters. Similarly, when implementing accessors for private member data, you should in most cases a const. This will ensure that if the object that you're operating on is passed as const, methods that do not affect the data stored in the object still work as they should and can be called. For example, for an object containing a person, a getName should a const data type where as walk might be non-const as it might change some internal data in the Person such as tiredness.

It is common practice to avoid using the keyword since it can obfuscate code if not properly used or it can cause programmers to accidentally misuse large structures thinking them to be simple types. If used, define a set of rules for the types you rename and be sure to document them.

volatile
This keyword informs the compiler that the variable it is qualifying as volatile (can change at anytime) is excluded from any optimization techniques. Usage of this variable should be reserved for variables that are known to be modified due to an external influence of a program (whether it's hardware update, third party application, or another thread in the application).

Since the volatile keyword impacts performance, you should consider a different design that avoids this situation: most platforms where this keyword is necessary provide an alternative that helps maintain scalable performance.

Note that using volatile was not intended to be used as a threading or synchronization primitive, nor are operations on a volatile variable guaranteed to be atomic.

Pointer declaration
Due to historical reasons some programmers refer to a specific use as:

The second variation is by far the preferred by C++ programmers and will help identify a C programmer or legacy code.

One argument against the C++ code style version is when chaining declarations of more than one item, like:

As you can see, in this case, the C code style makes it more obvious that ptrA and ptrB are pointers to ints, and the C++ code style makes it less obvious that ptrD is an int, not a pointer to an int.

It is rare to use chains of multiple objects in C++ code with the exception of the basic types and even so it is not often used and it is extremely rare to see it used in pointers or other complex types, since it will make it harder to for a human to visually parse the code.


text: C++ Programming/Code/Variables/Examples/Adds two numbers and prints their sum1


text:
C++ Programming/Code/API/Win32/Wrappers

Win32 API Wrappers
Since the Win32 API is C based and also a moving target and since some alterations are done in each OS version some wrappers were created, in this section you will find some of the approaches available to facilitate the use of the API in a C++ setup and provide abstraction from the low level stuff with higher level implementations of common needed features, dealing with the GUI, complex controls even communications and database access.

 * Microsoft Foundation Classes (MFC); : a C++ library for developing Windows applications and UI components. Created by Microsoft for the C++ Windows programmer as an abstraction layer for the Win32 API, the use of the new STL enabled capabilities is scarce on the MFC. It's also compatible with Windows CE (the pocket PC version of the OS). MFC was designed to use the Document-View pattern a variant of the Model View Controller (MVC) pattern. More info about MFC can be obtained on the Windows Programming Wikibook.

 * Windows Template Library (WTL); : a C++ library for developing Windows applications and UI components. It extends ATL (Active Template Library) and provides a set of classes for controls, dialogs, frame windows, GDI objects, and more. This library is not supported by Microsoft Services (but is used internally at MS and available for download at MSDN).

 * Win32 Foundation Classes (WFC); : (http://www.samblackburn.com/wfc/) a library of C++ classes that extend Microsoft Foundation Classes (MFC) to do NT specific things.

 * Borland Visual Component Library (VCL); : a Delphi/C++ library for developing Windows applications, UI components and different kinds of service applications. Created by Borland as an abstraction layer for the Win32 API, but also implementing many non-visual, and non windows-specific objects, like AnsiString class for example.

title: C++ Programming/Code/API/Win32/Wrappers


text: Template:Mentor needed

title: Template:Mentor needed