Henry Poon's Blog

Description of C++ Keywords

Source: The University of British Columbia

asm (seldom used)

  • Used to insert assembly language commands directly into the code. This function is very tricky to use even for professional programmers and can cause portability issues.

    asm(“instruction”);


auto

  • Used to declare local variables but is purely optional.

    auto int i = 5;

    The previous declaration thus has identical meaning to the following declaration.

    int i = 5;


bool (C++ only)

  • Used to declare a Boolean logic variable; a variable that can have the value true or false. This variable type is normally 8 bits (1 byte) long.

    bool t = true;


break

  • Used to break out of a loop independant of the loop condition. Also, used to finish a switch statement, keeping the program from “falling through” to the next case in the code.
    while(x < 100)
    {
        if(x < 0)
             break;
        cout << x << endl;
        x++;
    }
    

case

  • Used as a label to declare a single test in a switch statement.
    case 1: command1;
            command2;
            break;
    

catch (C++ only)

  • Used to handle exceptions generated by a throw statement.
    catch(const char* e)
    {
        //handle exception
    }
    

char

  • Used to declare character variables. This variable type is normally 8 bits (1 byte) long.

    char c = ‘h’;


class (C++ only)

  • Used to define a new class. Members of the class are private by default unless listed under the protected or public labels.
    class class-name : inheritance-list
    {
        public:
            public-members-list;
        protected:
            protected-members-list;
        private:
            private-members-list;
    } object-list;
    
    • class-name is the name of the class that is being created.
    • inheritance-list is the optional list of classes inherited by the new class.
    • public-members-list is the list of public members of the class.
    • protected-members-list is the list of protected members of the class.
    • private-members-list is the list of private members of the class.
    • object-list is an optional list used to immediately instantiate 1 or more instances of the class.
    class Date
    {
    public:
        void display();
    
    private:
        int day;
        int month;
        int year;
    }
    

const (C++ only)

  • Used to tell the compiler that a certain object should not be modified once it has been initialized.

    const int i = 5;

  • Used to declare a pointer so that the value of the pointer (the memory location to which it points) can be modified, but the data in the memory location cannot be changed.

    const int* j = new int(3);

  • Used to declare a pointer so the that value of the pointer (the memory location to which it points) cannot be modified, but the data in that memory location can be changed.

    int* const j = new int(3);

  • Used to declare a member function that does not modify the object’s state, meaning that it should be used for methods like print so that data in the object cannot be changed accidentally. If and attempt is made to modify the object in any way, a compilation error will be triggered.

    void print(bool verbose) const;


const_cast (C++ only, seldom used)

  • Used to remove the const protection on a variable as long as the original variable was not declared as a const. The target type must be the same as the original type.

    const_cast<target_type> (object);


continue

  • Used to jump to the next iteration of a loop. The following example will print out all of the numbers from 1 to 20 except for 10.
    for(int i = 0; i < 21; i++)
    {
        if(i == 10)
            continue;
        cout << i << endl;
    }
    

default

  • Used as a label to declare the default case of a switch statement.
    case 1:  command1;
             command2;
             break;
    
    default: command1;
             command2;
             break;
    

delete (C++ only)

  • Used to free memory allocated for a pointer back to the heap. The argument should have been allocated through a call to new. To delete an array, use the following form of delete: delete[]
    delete p;
    delete[] pArray;

do

  • Used to create a loop that is executed at least once. The terminating condition is tested at the end of the loop.
    do
    {
        cout << "hello worldn";
        i++;
    } while(i < 5)
    

double

  • Used to declare a double-precision floating-point type variable. This variable type is normally 64 bits (8 bytes) long.

    double d = 12.55;


dynamic_cast (C++ only, seldom used)

  • Used to cast from one type to another with a check performed at runtime. If the cast types are incompatible, NULL is returned.

    dynamic_cast<target_type> (object);


else

  • Used for an alternative condition in an if statement.
    if(i == 1)
    {
        // do something
    }
    else
    {
        // do something else
    }
    

enum

  • Used to define an enumerated type. Each of the names in the name-list are given a distinct value. This should be used in place of defining variables using “magic numbers” (eg. int Monday = 0, int Tuesday = 1, etc).
    enum name {name-list};
    • name is the name of the enumerated type that was created
    • name-list is the list of names of the elements
    enum weekdays {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};

explicit (C++ only)

  • Used to make sure that a constructoor is only used for the creation of new values and not used for the implicit conversion between two different types. It will only be be used if the initialization exactly matches the call to that constructor. This keyword is only needed with one-argument constructors.
    class vector
    {
        ...
        explicit vector(int v);
        ...
    }
    

    Using this keyword, some mysterious errors can be caught by the compiler like the following:

    vector<int> v(10);
    v = 5; // error, meant to write v[0] = 5
    

    The problem in this code if the explicit keyword was not specified is that the v = 5 statement would invoke the constructor, creating a new vector of size 5 and destroying the old one.


export (C++ only, seldom used)

  • Used to export a template to other modules. Most compilers require template definitions to be explicitly specified in the header file since the Comeau C++ compiler seems to be the only compiler that supports this keyword.
    // In MyTemplateFunction.h
    template
    void myTemplateFunction(const T &t1);
    
    // In MyTemplateFunction.cpp
    export template
    void myTemplateFunction(const T &t1)
    {
        ...
    }
    

extern

  • Used to inform the compiler of variables and functions that are defined outside of the current scope or module. Variables defined as extern will not have space allocated for them since they are defined elsewhere.

    extern char* message;


false (C++ only)

  • Used to represent the Boolean value false.

    bool b = false;


float

  • Used to declare a single-precision floating-point type variable. This variable<br> type is normally 32 bits (4 bytes) long.

    float f = 3.5;


for

  • Used to create a loop that is meant to initialize, test and update a variable.
    for(int i = 0; i < 10; i++)
    {
        cout << "i is " << i << endl;
    }
    

friend (C++ only)

  • Used to allow another class or function to have access to the private features of that class.
    friend void print(bool verbose);
    friend class Vector;

goto (seldom used)

  • Used to jump to another location in a function specified by a label. This is generally considered harmful and should not be used unless necessary.
    goto labelA;
    ...
    labelA:

if

  • Used to create a conditional branch statement so that different code can be executed under different conditions. The conditions are evaluated in the order that they appear in the code.
    if (i < 0)
    {
        cout << "i is negative";
    }
    else if(i == 0)
    {
        cout << "i is 0n";
    }
    else
    {
        cout << "i is posativen";
    }
    

inline (C++ only)

  • Used to tell the compiler that the function an its body are inserted into the calling code meaning that it has to expand the function in-place instead of just insert a call to the function. Functions that have static data, loops, switches or recursive calls cannot be inlined.
    inline int test(int A)
    {
        ...
    }
    

int

  • Used to declare an integer type variable. This variable type is normally 32 bits (4 bytes) long.

    int i = 3;


long

  • Used as a data type modifier for the int and double types to indicate that they may have more bytes then the type has available. This variable type is normally 32 or 64 bits (4 or 8 bytes) long.

    long int i = 100000;


mutable (C++ only)

  • Used to specify that it is a data field that can be modified even if another part of the data is declared const.

namespace (C++ only)

  • Used to create a new scope. Once created, the namespace must be refered to either directly or with the using keyword.
       namespace CartoonNameSpace
        {
            int HomersAge;
    
            void incrementHomersAge()
            {
                HomersAge++;
            }
        }
        int main() {
            ...
            CartoonNameSpace::HomersAge = 39;
            CartoonNameSpace::incrementHomersAge();
            cout << CartoonNameSpace::HomersAge << endl;
            ...
        }
    

new (C++ only)

  • Used to allocate a new block of memory for the given type from the heap, and return a pointer to that block of memory. Allocating arrays can be done by providing the size of the array in square brackets.
    pointer = new type;
    pointer = new type( initializer );
    pointer = new type[size];
    • pointer is a pointer to the type that you want to allocate the memory for
    • type is the type of the item that is to be stored in the memory that is allocated
    • initializer is the optional information for the constructor
    • size is the size of the array to create

operator (C++ only)

  • Used to specify that you are overloading an operator.
       return-type class-name::operator#(parameter-list)
        {
            ...
        }
    
    • return-type is the return type for the function
    • class-name is the name of the class that the operator is a part of. If it is not part of a class, this can be left out along with the ‘::.
    • # is the operator that is to be overloaded, such as ‘++’. You cannot overload the #, ##, ., :, .*, or ? tokens.
    • parameter-list is the list of parameters that the operator will take. For unary operators, parameter-list should be empty, and for binary operators, parameter-list should contain the operand on the right side of the operator (the operand on the left side is passed as this).
  • There are special conventions for some operators, such as the unary ++ and — operators.
    • The unary ++ operator has both prefix (++object and postfix (object++) versions.
    •    return-type class-name::operator++()
          {
              ...
          }
      

      overloads the prefix version (the value returned is the value of the object after it is incremented, so this is also known as the pre-increment version because the increment takes place before the value is returned). There is no parameter specified because ++ is a unary operator.

    •    return-type class-name::operator++( int )
          {
              ...
          }
      

      overloads the postfix version (the value returned is the value of the object before it is incremented, so this is also known as the post-increment version because the increment takes place after the value is returned). The parameter int is not really a parameter (++ is still a unary operator) but is there soley to differentiate the prefix and postfix versions.


private (C++ only)

  • Used within a class declaration to specify features of that class that can only be accessed by itself and its friends.
    class Date
    {
    public:
        void display();
    
    private:
        int day;
        int month;
        int year;
    }
  • Used to inherit a base class privately, which causes all public and protected members of the base class to become private members of the derived class.
    class AlarmClock : private Clock
    {
    public:
        void display();
    
    }

protected (C++ only)

  • Used within a class declaration to specify features of that class that are private to its own class, but can be inherited by a derived class.
    class Date
    {
    public:
        void display();
    protected:
        int day;
        int month;
        int year;
    }
  • Used to inherit a base class, which causes all public and protected members of the base class to become protected members of the derived class.
    class AlarmClock : protected Clock
    {
    public:
        void display()
    }

public (C++ only)

  • Used within a class declaration to specify features of that class that are accessable to everyone.
    class Date
    {
    public:
        void display();
    protected:
        int day;
        int month;
        int year;
    }
  • Used to inherit a base class publically, which causes all public and protected members of the base class to become public and protected members of the derived class.
    class AlarmClock : public Clock
    {
    public:
        void display()
    }

register

  • Used to reccommend that a varibale be placed into a processor register so that it is optimized for speed but the compiler is not obliged to do so. This keyword is rarely used anymore since compilers have become better than programmers at optimizing code.

reinterpret_cast (C++ only), seldom used

  • Used to change one data type in a non-portable way. It is normally used to cast between incompatible pointer types.

    reinterpret_cast<target_type> (object);


return

  • Used to cause the execution to jump from the current function back to the one that called it. An optional value can be returned but the function must specify the type that it will return.
    return;
    return 5;

short

  • Used as a data type modifier for the int type to indicate that there may be less bytes then the type has available. This variable type is normally 16or 32bits (2 or 4bytes) long.

    short int i = 5;


signed

  • Used to specify that the number type provided could potentially be negative, so it must be stored in a different format. This is the default representation that is chosen by most compilers if either signed or unsigned is not specified.

    signed int i = -12;


sizeof

  • Used to return the size of the object (in bytes) that is passed to it.
    int i = 5;
    int size = sizeof( i );

static

  • Used outside any function or class as a qualifier to a variable declaration makes the scope of the variable the file in which the variable is declared, and the extent is permanent (i.e., it is in the static segment).

    static int i;

  • Used inside a function as a qualifier to a variable declaration makes the scope of the variable the function in which the variable is declared, and the extent is permanent (i.e., it is in the static segment).
    void foo()
    {
        static int i;
    }
  • Used inside a class as a qualifier to a variable declaration makes the scope of the variable the class in which the variable is declared, and the extent is permanent (i.e., it is in the static segment).
    class bar
    {
        static int i;
    }
  • Used outside any class as a qualifier to a function declaration makes the scope of the function the file in which the function is declared. As with all functions, the instructions for the function are in the code segment.
    static void foo()
    {
    }
  • Used inside a class as a qualifier to a function (method) declaration makes the scope of the function the class in which the function is declared (as with all methods), and the instructions for the method are in the code segment (as for all functions). What is different is that a static method is invoked without requiring an object, using the qualifier syntax class::staticMethod( parameters ), although it can also be invoked on an object in the class in the usual way. Because no object is associated with a static method, only static member variables and other static member functions can be invoked by a static method.
    class bar
    {
        static void foo();
    }

    Note: A method in a class cannot be both “static” and “virtual”. The reason for this is that virtual functions have to know the object to which they apply (because of polymorphism) but static methods are not applied to an object.


static_cast (C++ only, seldom used)

  • Used for a normal conversion between types. No runtime checking is performed.

    static_cast<target_type> (object);


struct

  • Used to create a structure like a class, but the members are public by default instead of private. In C, structs can only contain data, cannot have inheritance and cannot have data with different visibilities.
    struct struct-name : inheritance-list
    {
            public-members-list;
        protected:
            protected-members-list;
        private:
            private-members-list;
    } object-list;
    • struct-name is the name of the struct that is being created.
    • inheritance-list is the optional list of structs inherited by the new struct.
    • public-members-list is the list of public members of the struct.
    • protected-members-list is the list of protected members of the struct.
    • private-members-list is the list of private members of the struct.
    • object-list is an optional list used to immediately instantiate 1 or more instances of the struct.
    struct Date
    {
        int day;
        int month;
        int year;
    }

switch

  • Used to test an expression of an integer value against many constant integer values and is commonly used to replace large if()…else if()… statements. Break statements are required between each case statement, otherwise execution will “fall-through” to the next case statement. The default case is optional. If provided, it will match any case not explicitly covered by the preceding cases in the switch statement.
    char keystroke = getch();
    switch( keystroke )
    {
        case 'a':
        case 'b':
        case 'c':
        case 'd':
            KeyABCDPressed();
            break;
        case 'e':
            KeyEPressed();
            break;
        default:
            UnknownKeyPressed();
            break;
    }
    

template (C++ only)

  • Used to create generic functions and can operate on data without knowing the nature of that data. They accomplish this by using a placeholder data-type for which many other data types can be substituted.
    template void genericSwap( X &a, X &b )
    {
        X tmp;
    
        tmp = a;
        a = b;
        b = tmp;
    }
    

this (C++ only)

  • Used as a pointer to the current object. All member functions of a class have this pointer.

    this.print();


throw (C++ only)

  • Used together with try and catch statements to create an exception handling system. Throw is used to generate an exception.
    try
    {
        cout << "Before throwing exception"<< endl;
        throw 42;
        cout << "Shouldn't ever see this"<< endl;
    }
    catch( int error )
    {
        cout << "Error: caught exception " << error << endl;
    }
    

true (C++ only)

  • Used to represent the Boolean value true.

    bool b = true;


try (C++ only)

  • Used to attempt to execute exception-generating code.
    try
    {
        cout << "Before throwing exception" << endl;
        throw 42;
        cout << "Shouldn't ever see this" << endl;
    }
    catch( int error )
    {
        cout << "Error: caught exception " << error << endl;
    }

typedef

  • Used to create a new type from an existing type.

    typedef int seconds;


typeid (C++ only, seldom used)

  • Used to get a reference to a type_info object that describes the object it was passed.

    typeid(object);


typename (C++ only)

  • Used to describe an undefined type or in place of the class keyword in a template declaration.

union

Used to create multiple data fields that will occupy the same memory location.

union Data
{
    int i;
    char c;
};

unsigned

  • Used to specify that the int or char provided can only be posative and can therefore contain a larger number since there is no need to worry about representation of negative numbers.

    signed int i = -12;


using (C++ only)

  • Used to import a namespace into the current scope.

    using namespace std;


virtual (C++ only)

  • Used to create virtual functions that can be overridden by derived functions.
    • A virtual function indicates that a function can be overridden in a subclass, and that the overridden function will actually be used.
    • When a base object pointer points to a derived object that contains a virual function, the decision about which version of that function to call is based on the type of object pointed to by the pointer, and this process happens at runtime.
    • A base object can point to different derived objects and have different versions of the virual function run.

    virtual void print();

  • Used to create a pure virtual function which is a virtual function that must be overriden by some derived class.

    virtual void print() = 0;

  • Note: A method in a class cannot be both “virtual” and “static”.

void

  • Used to denote functions that return no value.
    void print()
    {
        cout << "printn";
    }
    
  • Used to create generic variables which can point to any type of data.
    void *p = 5;
    
  • Used to declare an empty parameter list.
    void print( void )
    {
        cout << "printn";
    }

volatile

  • Used to inform the compiler that the variables value can change in unexpected ways (i.e. through an interrupt), which could conflict with optimizations that the compiler might perform, so therefore the compiler will not optimize these variables.

    volatile Date d;


wchar_t

  • Used to declare a wide character variable. This variable type is normally 16 bits (2 bytes) long.

    wchar_t c = ‘c’;


while

  • Used as a looping construct that will evaluate a list of statements as long as the condition is true. Note: if the condition starts off as false, the list of statements will never be executed. (You can use a do loop to guarantee that the list of statements will be executed at least once.)
    bool done = false;
    while( !done )
    {
        ProcessData();
        if( StopLooping() )
        {
            done = true;
        }
    }

Copyright (C) 2000-2005, The University of British Columbia

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Next Post

Previous Post

1 Comment

  1. Kavindu Indramala 2018-01-22

    Thanks bro

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2024 Henry Poon's Blog

Theme by Anders Norén