Skip to main content

Language of C++

LanguageEdit

The C++ language has two main components: a direct mapping of hardware features provided primarily by the C subset, and zero-overhead abstractions based on those mappings. Stroustrup describes C++ as "a light-weight abstraction programming language [designed] for building and using efficient and elegant abstractions";[5] and "offering both hardware access and abstraction is the basis of C++. Doing it efficiently is what distinguishes it from other languages".[32]
C++ inherits most of C's syntax. The following is Bjarne Stroustrup's version of the Hello world program that uses the C++ Standard Library stream facility to write a message to standard output:[33][34]
#include <iostream>

int main()
{
 std::cout << "Hello, world!\n";
}
Within functions that define a non-void return type, failure to return a value before control reaches the end of the function results in undefined behaviour(compilers typically provide the means to issue a diagnostic in such a case).[35]The sole exception to this rule is the main function, which implicitly returns a value of zero.[36]

Object storageEdit

As in C, C++ supports four types of memory management: static storage duration objects, thread storage duration objects, automatic storage duration objects, and dynamic storage duration objects.[37]

Static storage duration objectsEdit

Static storage duration objects are created before main() is entered (see exceptions below) and destroyed in reverse order of creation after main()exits. The exact order of creation is not specified by the standard (though there are some rules defined below) to allow implementations some freedom in how to organize their implementation. More formally, objects of this type have a lifespan that "shall last for the duration of the program".[38]
Static storage duration objects are initialized in two phases. First, "static initialization" is performed, and only after all static initialization is performed, "dynamic initialization" is performed. In static initialization, all objects are first initialized with zeros; after that, all objects that have a constant initialization phase are initialized with the constant expression (i.e. variables initialized with a literal or constexpr). Though it is not specified in the standard, the static initialization phase can be completed at compile time and saved in the data partition of the executable. Dynamic initialization involves all object initialization done via a constructor or function call (unless the function is marked with constexpr, in C++11). The dynamic initialization order is defined as the order of declaration within the compilation unit (i.e. the same file). No guarantees are provided about the order of initialization between compilation units.

Thread storage duration objectsEdit

Variables of this type are very similar to Static Storage duration objects. The main difference is the creation time is just prior to thread creation and destruction is done after the thread has been joined.[39]

Automatic storage duration objectsEdit

The most common variable types in C++ are local variables inside a function or block, and temporary variables.[40] The common feature about automatic variables is that they have a lifetime that is limited to the scope of the variable. They are created and potentially initialized at the point of declaration (see below for details) and destroyed in the reverse order of creation when the scope is left.
Local variables are created as the point of execution passes the declaration point. If the variable has a constructor or initializer this is used to define the initial state of the object. Local variables are destroyed when the local block or function that they are declared in is closed. C++ destructors for local variables are called at the end of the object lifetime, allowing a discipline for automatic resource management termed RAII, which is widely used in C++.
Member variables are created when the parent object is created. Array members are initialized from 0 to the last member of the array in order. Member variables are destroyed when the parent object is destroyed in the reverse order of creation. i.e. If the parent is an "automatic object" then it will be destroyed when it goes out of scope which triggers the destruction of all its members.
Temporary variables are created as the result of expression evaluation and are destroyed when the statement containing the expression has been fully evaluated (usually at the ; at the end of a statement).

Dynamic storage duration objectsEdit

Main article: new and delete (C++)
These objects have a dynamic lifespan and are created with a call to new and destroyed explicitly with a call to delete.[41]

TemplatesEdit

C++ templates enable generic programming. C++ supports function, class, alias and variable templates. Templates may be parameterized by types, compile-time constants, and other templates. Templates are implemented byinstantiation at compile-time. To instantiate a template, compilers substitute specific arguments for a template's parameters to generate a concrete function or class instance. Some substitutions are not possible; these are eliminated by an overload resolution policy described by the phrase "Substitution failure is not an error" (SFINAE). Templates are a powerful tool that can be used forgeneric programmingtemplate metaprogramming, and code optimization, but this power implies a cost. Template use may increase code size, because each template instantiation produces a copy of the template code: one for each set of template arguments, however, this is the same or smaller amount of code that would be generated if the code was written by hand.[42] This is in contrast to run-time generics seen in other languages (e.g., Java) where at compile-time the type is erased and a single template body is preserved.
Templates are different from macros: while both of these compile-time language features enable conditional compilation, templates are not restricted to lexical substitution. Templates are aware of the semantics and type system of their companion language, as well as all compile-time type definitions, and can perform high-level operations including programmatic flow control based on evaluation of strictly type-checked parameters. Macros are capable of conditional control over compilation based on predetermined criteria, but cannot instantiate new types, recurse, or perform type evaluation and in effect are limited to pre-compilation text-substitution and text-inclusion/exclusion. In other words, macros can control compilation flow based on pre-defined symbols but cannot, unlike templates, independently instantiate new symbols. Templates are a tool for static polymorphism (see below) and generic programming.
In addition, templates are a compile time mechanism in C++ that is Turing-complete, meaning that any computation expressible by a computer program can be computed, in some form, by a template metaprogram prior to runtime.
In summary, a template is a compile-time parameterized function or class written without knowledge of the specific arguments used to instantiate it. After instantiation, the resulting code is equivalent to code written specifically for the passed arguments. In this manner, templates provide a way to decouple generic, broadly applicable aspects of functions and classes (encoded in templates) from specific aspects (encoded in template parameters) without sacrificing performance due to abstraction.

ObjectsEdit

Main article: C++ classes
C++ introduces object-oriented programming (OOP) features to C. It offersclasses, which provide the four features commonly present in OOP (and some non-OOP) languages: abstractionencapsulationinheritance, andpolymorphism. One distinguishing feature of C++ classes compared to classes in other programming languages is support for deterministic destructors, which in turn provide support for the Resource Acquisition is Initialization (RAII) concept.

EncapsulationEdit

Encapsulation is the hiding of information to ensure that data structures and operators are used as intended and to make the usage model more obvious to the developer. C++ provides the ability to define classes and functions as its primary encapsulation mechanisms. Within a class, members can be declared as either public, protected, or private to explicitly enforce encapsulation. A public member of the class is accessible to any function. A private member is accessible only to functions that are members of that class and to functions and classes explicitly granted access permission by the class ("friends"). A protected member is accessible to members of classes that inherit from the class in addition to the class itself and any friends.
The OO principle is that all of the functions (and only the functions) that access the internal representation of a type should be encapsulated within the type definition. C++ supports this (via member functions and friend functions), but does not enforce it: the programmer can declare parts or all of the representation of a type to be public, and is allowed to make public entities that are not part of the representation of the type. Therefore, C++ supports not just OO programming, but other weaker decomposition paradigms, like modular programming.
It is generally considered good practice to make all data private or protected, and to make public only those functions that are part of a minimal interface for users of the class. This can hide the details of data implementation, allowing the designer to later fundamentally change the implementation without changing the interface in any way.[43][44]

InheritanceEdit

Inheritance allows one data type to acquire properties of other data types. Inheritance from a base class may be declared as public, protected, or private. This access specifier determines whether unrelated and derived classes can access the inherited public and protected members of the base class. Only public inheritance corresponds to what is usually meant by "inheritance". The other two forms are much less frequently used. If the access specifier is omitted, a "class" inherits privately, while a "struct" inherits publicly. Base classes may be declared as virtual; this is called virtual inheritance. Virtual inheritance ensures that only one instance of a base class exists in the inheritance graph, avoiding some of the ambiguity problems of multiple inheritance.
Multiple inheritance is a C++ feature not found in most other languages, allowing a class to be derived from more than one base class; this allows for more elaborate inheritance relationships. For example, a "Flying Cat" class can inherit from both "Cat" and "Flying Mammal". Some other languages, such asC# or Java, accomplish something similar (although more limited) by allowing inheritance of multiple interfaces while restricting the number of base classes to one (interfaces, unlike classes, provide only declarations of member functions, no implementation or member data). An interface as in C# and Java can be defined in C++ as a class containing only pure virtual functions, often known as an abstract base class or "ABC". The member functions of such an abstract base class are normally explicitly defined in the derived class, not inherited implicitly. C++ virtual inheritance exhibits an ambiguity resolution feature called dominance.

Operators and operator overloadingEdit

Operators that cannot be overloaded
OperatorSymbol
Scope resolution operator::
Conditional operator?:
dot operator.
Member selection operator.*
"sizeof" operatorsizeof
"typeid" operatortypeid
Main article: Operators in C and C++
C++ provides more than 35 operators, covering basic arithmetic, bit manipulation, indirection, comparisons, logical operations and others. Almost all operators can be overloaded for user-defined types, with a few notable exceptions such as member access (. and .*) as well as the conditional operator. The rich set of overloadable operators is central to making user-defined types in C++ seem like built-in types.
Overloadable operators are also an essential part of many advanced C++ programming techniques, such as smart pointers. Overloading an operator does not change the precedence of calculations involving the operator, nor does it change the number of operands that the operator uses (any operand may however be ignored by the operator, though it will be evaluated prior to execution). Overloaded "&&" and "||" operators lose their short-circuit evaluation property.

PolymorphismEdit

Polymorphism enables one common interface for many implementations, and for objects to act differently under different circumstances.
C++ supports several kinds of static (resolved at compile-time) and dynamic(resolved at run-timepolymorphisms, supported by the language features described above. Compile-time polymorphism does not allow for certain run-time decisions, while runtime polymorphism typically incurs a performance penalty.

Static polymorphismEdit

Function overloading allows programs to declare multiple functions having the same name but with different arguments (i.e. ad hoc polymorphism). The functions are distinguished by the number or types of their formal parameters. Thus, the same function name can refer to different functions depending on the context in which it is used. The type returned by the function is not used to distinguish overloaded functions and would result in a compile-time error message.
When declaring a function, a programmer can specify for one or more parameters a default value. Doing so allows the parameters with defaults to optionally be omitted when the function is called, in which case the default arguments will be used. When a function is called with fewer arguments than there are declared parameters, explicit arguments are matched to parameters in left-to-right order, with any unmatched parameters at the end of the parameter list being assigned their default arguments. In many cases, specifying default arguments in a single function declaration is preferable to providing overloaded function definitions with different numbers of parameters.
Templates in C++ provide a sophisticated mechanism for writing generic, polymorphic code (i.e. parametric polymorphism). In particular, through theCuriously Recurring Template Pattern, it's possible to implement a form of static polymorphism that closely mimics the syntax for overriding virtual functions. Because C++ templates are type-aware and Turing-complete, they can also be used to let the compiler resolve recursive conditionals and generate substantial programs through template metaprogramming. Contrary to some opinion, template code will not generate a bulk code after compilation with the proper compiler settings.[42]

Dynamic polymorphismEdit

InheritanceEdit
See also: Subtyping
Variable pointers and references to a base class type in C++ can also refer to objects of any derived classes of that type. This allows arrays and other kinds of containers to hold pointers to objects of differing types (references cannot be directly held in containers). This enables dynamic (run-time) polymorphism, where the referred objects can behave differently depending on their (actual, derived) types
C++ also provides the dynamic_cast operator, which allows code to safely attempt conversion of an object, via a base reference/pointer, to a more derived type: downcasting. The attempt is necessary as often one does not know which derived type is referenced. (Upcasting, conversion to a more general type, can always be checked/performed at compile-time via static_cast, as ancestral classes are specified in the derived class's interface, visible to all callers.) dynamic_cast relies on run-time type information (RTTI), metadata in the program that enables differentiating types and their relationships. If a dynamic_cast to a pointer fails, the result is the nullptr constant, whereas if the destination is a reference (which cannot be null), the cast throws an exception. Objects known to be of a certain derived type can be cast to that withstatic_cast, bypassing RTTI and the safe runtime type-checking of dynamic_cast, so this should be used only if the programmer is very confident the cast is, and will always be, valid.
Virtual member functionsEdit
Ordinarily, when a function in a derived class overrides a function in a base class, the function to call is determined by the type of the object. A given function is overridden when there exists no difference in the number or type of parameters between two or more definitions of that function. Hence, at compile time, it may not be possible to determine the type of the object and therefore the correct function to call, given only a base class pointer; the decision is therefore put off until runtime. This is called dynamic dispatchVirtual member functions or methods[45] allow the most specific implementation of the function to be called, according to the actual run-time type of the object. In C++ implementations, this is commonly done using virtual function tables. If the object type is known, this may be bypassed by prepending a fully qualified class name before the function call, but in general calls to virtual functions are resolved at run time.
In addition to standard member functions, operator overloads and destructors can be virtual. As a rule of thumb, if any function in the class is virtual, the destructor should be as well. As the type of an object at its creation is known at compile time, constructors, and by extension copy constructors, cannot be virtual. Nonetheless a situation may arise where a copy of an object needs to be created when a pointer to a derived object is passed as a pointer to a base object. In such a case, a common solution is to create a clone() (or similar) virtual function that creates and returns a copy of the derived class when called.
A member function can also be made "pure virtual" by appending it with = 0after the closing parenthesis and before the semicolon. A class containing a pure virtual function is called an abstract data type. Objects cannot be created from abstract data types; they can only be derived from. Any derived class inherits the virtual function as pure and must provide a non-pure definition of it (and all other pure virtual functions) before objects of the derived class can be created. A program that attempts to create an object of a class with a pure virtual member function or inherited pure virtual member function is ill-formed.

Lambda expressionsEdit

C++ provides support for anonymous functions, which are also known as lambda expressions and have the following form:
[capture](parameters) -> return_type { function_body }
The [capture] list supports the definition of closures. Such lambda expressions are defined in the standard as syntactic sugar for an unnamedfunction object. An example lambda function may be defined as follows:
[](int x, int y) -> int { return x + y; }

Exception handlingEdit

Exception handling is used to communicate the existence of a runtime problem or error from where it was detected to where the issue can be handled.[46] It permits this to be done in a uniform manner and separately from the main code, while detecting all errors.[47] Should an error occur, an exception is thrown (raised), which is then caught by the nearest suitable exception handler. The exception causes the current scope to be exited, and also each outer scope (propagation) until a suitable handler is found, calling in turn the destructors of any objects in these exited scopes.[48] At the same time, an exception is presented as an object carrying the data about the detected problem.[49]
The exception-causing code is placed inside a try block. The exceptions are handled in separate catch blocks (the handlers); each try block can have multiple exception handlers, as it is visible in the example below.[50]
#include <iostream>
#include <vector>
#include <stdexcept>

int main() {
    try {
        std::vector<int> vec{3,4,3,1};
        int i{vec.at(4)}; // Throws an exception, std::out_of_range (indexing for vec is from 0-3 not 1-4)
    }

    // An exception handler, catches std::out_of_range, which is thrown by vec.at(4)
    catch (std::out_of_range& e) {
        std::cerr << "Accessing a non-existent element: " << e.what() << '\n';
    }

    // To catch any other standard library exceptions (they derive from std::exception)
    catch (std::exception& e) {
        std::cerr << "Exception thrown: " << e.what() << '\n';
    }

    // Catch any unrecognised exceptions (i.e. those which don't derive from std::exception)
    catch (...) {
        std::cerr << "Some fatal error\n";
    }
}
It is also possible to raise exceptions purposefully, using the throw keyword; these exceptions are handled in the usual way. In some cases, exceptions cannot be used due to technical reasons. One such example is a critical component of an embedded system, where every operation must be guaranteed to complete within a specified amount of time. This cannot be determined with exceptions as no tools exist to determine the minimum time required for an exception to be handled.[51]
source wikipedia

Comments

Popular posts from this blog

QBasic and its history

QBasic Not to be confused with  Quick Basic . QBasic Paradigm Procedural Developer Microsoft First appeared 1991 ; 25 years ago OS MS-DOS ,  Windows 95 ,  Windows 98 ,  Windows Me ,  PC DOS ,  OS/2 , eComStation License Part of the operating system (a variety of  closed-source  licenses) Website www .microsoft .com Influenced by QuickBASIC ,  GW-BASIC Influenced QB64 ,  Small Basic QBasic  ( Microsoft  Quick Beginners All purpose Symbolic Instruction Code ) is an  IDE  and  interpreter  for a variety of the  BASIC programming language  which is based on  QuickBASIC . Code entered into the IDE is compiled to an intermediate representation , and this  IR  is immediately interpreted on demand within the IDE. [1]  It can run under nearly all versions of  DOS  and  Windows , or through  DOSBox / DOSEMU , on  Linux  and  FreeBSD . [2]  For its time, QBasic provided a state-of-the-art IDE, including a  debugger  with features such as on-the-fly expression evaluation and

Top 10 keyboard shortcuts everyone should know

Top 10 keyboard shortcuts everyone should know Using keyboard shortcuts can greatly increase your productivity, reduce repetitive strain, and help keep you focused. For example, to copy text, you can highlight text and press the Ctrl + C shortcut. The shortcut is faster than moving your hands from the keyboard, highlighting with the mouse, choosing copy from the file menu, and then returning to the keyboard. Below are the top 10 keyboard shortcuts we recommend everyone memorize and use. Ctrl + C or Ctrl + Insert and Ctrl + X Both  Ctrl + C  and  Ctrl +  Insert  will  copy  the  highlighted  text or selected item. If you want to  cut  instead of copy press  Ctrl + X . Apple  computer users can substitute the Ctrl key for the  command (cmd) key  on their computers. For example, pressing  Cmd + C  copies the highlighted text. Ctrl + V or Shift + Insert Both the  Ctrl + V  and  Shift + Insert  will  paste  the text or object that's in the clipboard . For Apple computer

computer network

A network may refer to any of the following: 1. A network is a collection of computers, servers, mainframes, network devices, peripherals, or other devices connected to one another to allow the sharing of data. An excellent example of a network is the Internet, which connects millions of people all over the world. Below is an example image of a home network with multiple computers and other network devices all connected to each other and the Internet. Computer network Examples of network devices *Desktop computers, laptops, mainframes, and servers *Consoles and thin clients *Firewalls *Bridges *Repeaters *Network Interface cards *Switches, hubs, modems, and routers *Smartphones and tablets *Webcams *Network topologies and types of networks The term network topology describes the relationship of connected devices in terms of a geometric graph. Devices are represented as vertices, and their connections are represented as edges on the graph. It describes