Your browser doesn't support JavaScript cpp Archives - Page 2 of 3 - Windows Programming

The C++ Standard Template Library (STL)

The standard template library (STL) is a set of template classes and functions that supply the programmer with common data structures and functions such as lists, stacks, arrays, sorting etc utilized through templates.

The STL is comprised of the following componentsContainers for storing information
Iterators for accessing the information stored
Algorithms for manipulating the content of the containers

Containers

Containers are STL classes that are used to store data. Each container class defines a set of functions that may be applied to the container. For example, a list container includes functions that insert, delete, and merge elements. A stack includes functions that push and pop values. STL supplies provide the following container classes:Sequential containers
Associative containers
Container Adapters

Sequential Containers

These are ordered collections used to hold data in a sequential fashion. Each element holds a position and that position depends on the time and place of insertion. Adding any objects to the end of a vector means that the object will appear in the order that were inserted. Sequential containers are characterized by a fast insertion time, but are relatively slow in find operations.

The STL provides five sequence container classes:

std::vector – The vector class implements a dynamic array and thus can grow as needed. Although a vector is dynamic, it still uses the standard array subscript notation to access its elements. Compared to the other dynamic sequence containers,vectors are very efficient at accessing elements and relatively efficient adding or removing elements from its end. For operations that involve inserting or removing elements at positions other than the end, they perform worse than the other sequence container classes

std::deque – Similar to std::vector except that it allows for new elements to be inserted or removed at the beginning. Unlike vectors, deques are not guaranteed to store all its elements in contiguous storage locations. Attempting to access and elements by offsetting a pointer to another element will result in undefined behavior. For operations that involve frequent insertion or removals of elements at positions other than the beginning or the end, deques are less efficient than lists and forward lists.

std::list – Are sequence containers that allow constant time insert and erase operations anywhere within the sequence, and iteration in both directions. They Operate like a doubly linked list.Compared to other standard sequence containers lists perform generally better in inserting, extracting and moving elements in any position within the container. The main drawback of lists and forward_lists compared to these other sequence containers is that they lack direct access to the elements by their position and thus searching can take extra time. They also consume some extra memory to keep the linking information associated to each element.

std::forward_list – Similar to a std::list except that it is a singly linked list of elements that allows iteration only in one direction. Compared to other base standard sequence containers forward_list perform generally better in inserting, extracting and moving elements in any position within the container. The main drawback of forward_lists is that like the standard list they lack direct access to the elements by their positionand consume extra resources to keep the linking information current.

std::array class – Is a templated class that provides many benefits over built-in arrays, such as maintaining the array size preventing automatic decay into a pointer, providing bounds checking, and allowing the use of C++ container operations.

Associative Containers

Associative containers utilise sorted data structures that can be quickly searched using keys. This results in slower insertion times, but presents significant advantages when it comes to searching.

The associative containers supplied by STL are –std::set 
std::unordered_set
std::map 
std::unordered_map
std::multiset 
std::unordered_multiset
std::multimap
std::unordered_multimap

Container Adapters

Container Adapters offer limited functionality oriented towards a particular container class and providing a more relevant set of functionality. The main adapter classes are:

std::stack — Stores elements in a LIFO (last-in-first-out) fashion, allowing elements to be inserted (pushed) and removed (popped) at the to.

std::queue — Stores elements in FIFO (first-in-first-out) fashion, allowing the first element to be removed in the order they’re inserted.

std::priority_queue — Stores elements in a sorted order, such that the one whose value is evaluated to be the highest is always first in the queue.

Iterators

Iterators are are template classes that act like pointers. They provide the means to cycle and manipulate the contents of a container in much the same way that you would use a pointer to cycle through an array. There are five types of iterators:Bidirectional iterator – Store and retrieve values. Forward and backward moving.
Forward iterator – Store and retrieve values. Forward moving only.
Input iterator – Retrieve, but not store values. Forward moving only.
Output iterator – Store, but not retrieve values. Forward moving only.
Random access iterator – Store and retrieve values. Elements may be accessed randomly.

STL Algorithms

Algorithms act on containers. Each container provides support for its own basic operations however the standard algorithms header provides a more extensive range of functionality. One algorithm function can be used on any type of container. Algorithms from STL are tried and tested saving time & effort when manipulating data. The algorithm library covers sorting, searching,Modifying & Non modifying and Minimum and Maximum operations.

Vector examples

The following code sample uses vectors to create and manipulate an int vector#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector <int> v; // create zero-length vector unsigned int i; cout << "initial size of vector v = " << v.size() << endl;// display original size of v for(i=0; i<20; i++) v.push_back(i); cout << "new size of vector v = " << v.size() << endl; // display new size of vector v cout << "Current contents of vector v:\n"; for(i=0; i<v.size(); i++) cout << v[i] << " ";// display contents of vector v cout << endl; cout << "add 5 elements to vector v:\n"; for(i=0; i<5; i++) v.push_back(i+10);//add 5 more values to vector cout << "new size of vector = " << v.size() << endl;// display current size of v cout << "Current contents of vector v:\n"; for(i=0; i<v.size(); i++) cout << v[i] << " ";// display contents of vector v cout << endl; sort(v.begin(), v.end());//sort contents of vector v cout << "Sort contents of vector v and list\n"; for(i=0; i<v.size(); i++) cout << v[i] << " "; // display contents of sorted vector cout << endl; vector <int> v1(10,5);//create new int vector v1 and initialise elements to 5 cout << "create new int vector v1. Initialise elements to 5. Merge with vector v\n"; for(i=0; i < v1.size();i++)v.push_back(v1[i]);// merged vector v and v1 for(i=0; i < v.size(); i++)cout << v[i] << " ";//display contents of v1cout << endl;cout << "Clear contents of vector v\n"; v.clear();// clear contents of vectorcout << "new size of vector = " << v.size() << endl;return 0;}

The following code sample uses template lists to create and manipulate an int vector#include <iostream> #include <list> using namespace std; int main() { list <int> lst;// create an empty list lst list <int> lst1; // create an empty list lst1 cout << "create random integer lists: " << endl; int rn; for(int a=10;a>0;a=a-1) { lst.push_back(rand()); //add random number to lst lst.push_back(rand()); //add random number to lst1 } list<int>::iterator p = lst.begin();//create pointer p and set to start of lst cout << "output contents of lst: " << endl; while(p != lst.end()) { //iterate through entire lst cout << *p << " "; //output lst value cout << endl; p++; } lst.sort(); cout << "sort lst: " << endl; p = lst.begin(); while(p != lst.end()) { cout << *p << " ";//output lst element cout << endl; p++; } cout << "merge and sort" << endl; lst.merge(lst1);//merge lst and lst lst.sort();//sort lst p = lst.begin(); while(p != lst.end()) { cout << *p << " ";//output lst cout << endl; p++; } }

Templates

A template is a parameterised definition used to create a generic function or class. Templates allow the same function or class to work with different data types without having to write a separate version for each type.

A function template starts with the keyword template, followed by one or more template parameters enclosed in angle brackets. The template parameter can then be used in place of a normal data type within the function definition.

The general form of a function template is:−

template <class T> T someFunction(T arg) { }

The template parameter T represents a data type. When the function is called, the compiler can determine the appropriate type from the arguments and instantiate a version of the function for that type.

The following example uses a function template to return the larger of two values. The same template is used with int, double, and string values:−

#include <iostream>
#include <string>

using namespace std;

// Creates a template with the parameter type T
template <typename T>

// Template function accepts two parameters of type T
T Max(T a, T b)
{
    if (a > b)
    {
        return a;
    }

    return b;
}

int main()
{
    int i = 20;
    int j = 10;

    // The template is instantiated for int values
    cout << "Max(i, j): " << Max(i, j) << endl;

    double f1 = 13.5;
    double f2 = 20.7;

    // The template is instantiated for double values
    cout << "Max(f1, f2): " << Max(f1, f2) << endl;

    string s1 = "a";
    string s2 = "b";

    // The template is instantiated for string values
    cout << "Max(s1, s2): " << Max(s1, s2) << endl;

    return 0;
}

When Max(i, j) is called, the compiler determines that T is int and instantiates the function for int values.

When Max(f1, f2) is called, T is double, so the function is instantiated for double values.

Finally, when Max(s1, s2) is called, T is string, so the function is instantiated for string values.

The important point is that one function template can be used with several different data types, provided those types support the operations used by the template. In this example, the type must support the > operator because Max() uses it to compare the two values.

A Function with Multiple Generic Types

A comma-separated list can be used to define more than one generic type in a template declaration. Each template parameter can represent a different data type.

The following example defines a function template with two generic types, type1 and type2. The function accepts two parameters, which can be different types:

#include <iostream>

using namespace std;

// Creates a template with two different parameter types
template <class type1, class type2>

void myfunc(type1 x, type2 y)
{
    cout << x << ' ' << y << '\n';
}

int main()
{
    // type1 is const char* and type2 is int
    myfunc("5x2=", 10);

    // type1 is int and type2 is const char*
    myfunc(10, "=9+1");

    return 0;
}

In the first call, type1 is deduced as const char* and type2 as int. In the second call, type1 is int and type2 is const char*.

The same function template can therefore be used with different combinations of data types.

For example, if actual char values were required, the function could also be called like this:

myfunc('A', 10); myfunc(10, 'B');

Here, type1 and type2 are deduced as char and int, or int and char, respectively.

Declaring Templates with Default Parameters

A template function can combine generic template parameters with ordinary function parameters. Ordinary function parameters can also have default values.

In the following example, FunctionX() has one generic parameter, X, and one ordinary int parameter. The ordinary parameter has a default value of 0.

#include <iostream>
using namespace std;
template <typename X> 
//creates template function with template parameter and standard parameter with default value 0
void FunctionX(X value1,int value2=0)
{
if (value2!=NULL)
{
cout << value1 << " ";
cout << value2 ; 
}
else
{
cout << "float value=" << value1 << endl;
}
}
int main()
{
float b=4.33;
// calls template function using only template parameter.
FunctionX(b); 
// calls template function using template parameter and standard parameter.
FunctionX( "float value cast to int =",b);
return 0;
}

To the first call, FunctionX(b), the compiler deduces X as float. Since no second argument is supplied, value2 uses its default value of 0.

In the second call, X is deduced as const char*, because the first argument is a string literal. The second argument, b, is a float and is converted to int because value2 is declared as an int.

Default Template Parameters

A template parameter can also have a default type. This is different from giving a function parameter a default value.

For example:

#include <iostream>

using namespace std;

template <typename X = int>
void FunctionX(X value)
{
    cout << value << endl;
}

int main()
{
    FunctionX(10);       // X is deduced as int
    FunctionX(4.33);     // X is deduced as double
    FunctionX('A');      // X is deduced as char

    return 0;
}

In this example, X has a default type of int:

template <typename X=int>

The function can still be used with other types because the compiler can deduce X from the argument. Therefore, the default int is only used when no other type is provided or can be deduced.

Overloading a Generic Function

Template functions can be overloaded with other functions having the same name but different parameter types.

In the following example, the function template T() can accept two values of the same type. A separate non-template version of T() is also provided that specifically accepts two int parameters.

When T() is called with int values, the non-template overloaded function is selected. When it is called with const char* values, the template function is used.

#include <iostream>

using namespace std;

// Generic template function
template <class X>
void T(X a, X b)
{
    cout << "Inside template T." << endl;
    cout << a << b << endl;
}

// Non-template overload specifically for int values
void T(int& a, int& b)
{
    cout << "Inside overloaded function" << endl;
    cout << a << " X " << b << " = " << a * b << endl;
}

int main()
{
    int i = 10;
    int j = 20;

    const char* word1 = "hello ";
    const char* word2 = "world ";

    // Calls the generic template function
    T(word1, word2);

    // Calls the non-template overloaded function
    T(i, j);

    return 0;
}

The first call:

T(word1, word2);

uses the template function. The compiler deduces X as const char*.

The second call:

T(i, j);

matches both the template and the non-template function, but the non-template overload is selected because it provides a direct match for the int arguments.

The result is that the int version performs multiplication, while other suitable types can use the generic template.

It is important to distinguish overloading from overriding. Overloading means providing multiple functions with the same name but different parameter lists. Overriding is a feature of inheritance where a derived class provides a new implementation of a virtual function inherited from a base class.

Variadic functions

Variadic templates allow a function or class template to accept an arbitrary number of template arguments. They were introduced in C++11.

The following example uses a variadic function template to add together an arbitrary number of values:

#include <iostream>

using namespace std;

// Base case - accepts one argument
template <typename T>
double sum(T t)
{
    return t;
}

// Recursive case - accepts one argument followed by any number of arguments
template <typename T, typename... Rest>
double sum(T t, Rest... rest)
{
    return t + sum(rest...);
}

int main()
{
    double dTotal = 0;

    dTotal = sum(33, 3.14, 4.56, 1.1111, 44, 55);

    cout << "dResult = " << dTotal << endl;

    return 0;
}

The function is defined in two parts. The first is the base case:

template <class T> double sum(T t) { return t; }

This function accepts a single argument and simply returns it. It provides the stopping point for the recursion.

The second is the recursive case:

template <typename T,typename ... Rest> double sum(T t,Rest... rest) { return t + sum(rest...); }

Here, T represents the type of the first argument, while Rest… represents a parameter pack containing all the remaining arguments.

When the following call is made:

sum(33, 3.14, 4.56, 1.1111, 44, 55);

the recursive function takes the first argument and passes the remaining arguments to another call to sum():

33 + sum(3.14, 4.56, 1.1111, 44, 55)

This continues until only one argument remains. At that point, the base-case function is called:

The result is approximately:

33 + 3.14 + 4.56 + 1.1111 + 44 + 55
140.7111

The sizeof... operator can be used with a parameter pack to determine how many elements it contains. For example:

cout << sizeof...(rest) << endl;

In the first invocation of the recursive function, rest contains five arguments, so sizeof...(rest) returns 5. Each subsequent recursive call has one fewer argument in its parameter pack.

Variadic templates are useful when a function needs to work with an arbitrary number of arguments. They can avoid the need to write separate functions for different numbers of parameters, making the resulting code more flexible and reusable.

Class Template

It is also possible to create classes that use templates. A class template defines a class that can work with different data types. A template parameter can be used as a type for data members, function parameters and return values within the class.

The following example creates a class template called Compare. It stores two values of the template type and provides a member function that returns the larger value.

The class template is declared using:

#include <iostream>

using namespace std;

// Class template
template <class T>
class Compare
{
    T x, y;       // Data members use the template type

public:

    // Constructor
    Compare(T first, T second)
    {
        x = first;
        y = second;
    }

    // Member function declaration
    T getMax();
};

// Member function definition
template <class T>
T Compare<T>::getMax()
{
    T retval;

    retval = x > y ? x : y;

    return retval;
}

int main()
{
    // Creates a Compare object using int as the template type
    Compare<int> templateObject(10, 22);

    cout << templateObject.getMax() << endl;

    // Creates a Compare object using char as the template type
    Compare<char> templateObjectC('e', 'z');

    cout << templateObjectC.getMax() << endl;

    return 0;
}

The class template is declared using:

template <class T> class Compare

Here, T is a template parameter that represents a data type. It is used for the two data members:

T x, y;

It is also used for the constructor parameters and the return type of getMax().

When the following object is created:

Compare <int> templateObject(10, 22);

the template parameter T is replaced by int. The resulting class therefore stores two int values.

The second object is created with:

Compare <char> templateObject('e', 'z');

Here, T is char, so the class stores two char values.

The same class template can therefore be used with different data types without having to write a separate class for each type.

The member function is defined outside the class using:

template <class T> T Compare<T>::getMax();

Compare<T>::getMax() tells the compiler that getMax() is a member of the class template Compare and that it uses the same template parameter T as the class.

Polymorphism

Polymorphism refers to the ability to access different types of member functions depending on the type of object that invokes the function. Polymorphism can be static or dynamic. C++ supports compile-time polymorphism and run-time polymorphism.

With compile-time polymorphism, the compiler determines which function should be called. Function overloading and operator overloading are examples of compile-time polymorphism.

With run-time polymorphism, the function to be called is determined while the programme is running. This is commonly achieved using virtual functions and inheritance.

Compile-Time Polymorphism

This type of polymorphism involved either function or operator overloading

Function overloading

Function or method overloading is the ability to create multiple methods of the same name with different parameter implementations.  The compiler determines which function to call based on the arguments supplied.

In the example below, the first function is called when an int is supplied, the second when a char is supplied, and the third when two int values are supplied.

#include <iostream>

class Base
{
public:
    // Function with an int parameter
    void func(int x)
    {
        std::cout << "Value of x is " << x << std::endl;
    }

    // Function with a char parameter
    void func(char x)
    {
        std::cout << "Value of x is "
                  << x << " or "
                  << static_cast<int>(x) << std::endl;
    }

    // Function with two int parameters
    void func(int x, int y)
    {
        std::cout << "Value of x and y is "
                  << x << ", " << y << std::endl;
    }
};

int main()
{
    Base obj1;

    // Which function is called depends on the arguments supplied
    obj1.func(33);       // Calls the first func()
    obj1.func('!');      // Calls the second func()
    obj1.func(33, 66);   // Calls the third func()

    return 0;
}
The output is:

Value of x is 33
Value of x is ! or 33
Value of x and y is 33, 66

The three functions all have the same name, func, but their parameter lists are different. The compiler uses the arguments supplied in each function call to determine which version should be used.

The conversion from char to int in the second function is used to display the numerical character code for !.

Operator overloading

Operator overloading allows the programmer to define the behaviour of an operator for a particular class. Almost all operators in C++ can be overloaded. To create an overloaded operator, an operator function is created to define the action of the overloaded operator. The function name is preceded by the keyword “operator” and then the symbol for the operator is defined. An overloaded operator function can have a return type and a parameter list.

Operators are commonly classified according to the number of operands they use. A unary operator operates on one operand, while a binary operator operates on two operands.

Overloading the Binary Addition Operator

The following example overloads the binary addition operator (+) so that two Area objects can be added together.

#include <iostream>

class Area
{
private:
    int x;
    int y;

public:
    Area(int a = 0, int b = 0)
    {
        x = a;
        y = b;
    }

    // Overloaded + operator
    Area operator+(const Area& rhs) const
    {
        Area returnObject;

        returnObject.x = x + rhs.x;
        returnObject.y = y + rhs.y;

        return returnObject;
    }

    void Print() const
    {
        std::cout << x << " " << y << std::endl;
    }
};

int main()
{
    Area c1(10, 5);
    Area c2(2, 4);

    Area c3 = c1 + c2;

    c3.Print();

    return 0;
}

The output is: 12 9.

The expression: c1 + c2 uses the overloaded + operator to add the corresponding x and y values from the two objects. In this example, it is equivalent to calling:c1.operator+(c2);.The resulting Area object is returned and used to initialise c3.

Overloading the unary increase and decrease operator 

The increment (++) and decrement (–) operators are unary operators because they operate on a single object.

Both operators can be overloaded as either prefix or postfix operators.

With the prefix form, the operator appears before the object:

With the postfix form, the operator appears after the object:

When overloading these operators, C++ uses an int parameter to distinguish the postfix version from the prefix version. The parameter is not normally used.

The following example overloads both the increment and decrement operators:

#include <iostream>

class Overloaded
{
private:
    int count;

public:
    Overloaded() : count(1) {}

    // Prefix increment
    void operator++()
    {
        ++count;
    }

    // Postfix increment
    void operator++(int)
    {
        count++;
    }

    // Prefix decrement
    void operator--()
    {
        --count;
    }

    // Postfix decrement
    void operator--(int)
    {
        count--;
    }

    void DisplayCount() const
    {
        std::cout << "Count: " << count << std::endl;
    }
};

int main()
{
    Overloaded value;

    ++value;              // Calls prefix increment
    value.DisplayCount();

    value++;              // Calls postfix increment
    value.DisplayCount();

    --value;              // Calls prefix decrement
    value.DisplayCount();

    value--;              // Calls postfix decrement
    value.DisplayCount();

    return 0;
}

The output is:

Count: 2
Count: 3
Count: 2
Count: 1

Dynamic or Run-Time Polymorphism

In contrast, with compile time polymorphism, the compiler determines which function call to bind to the object after deducing it at runtime. This allows different objects to respond differently to the same method call. In C++, run-time polymorphism is commonly implemented using virtual functions, allowing a base-class pointer or reference to call an overridden function in a derived class

Virtual function –  is a member function declared in a base class that can be overridden by a derived class. When a derived class object is accessed through a pointer or reference to the base class, a virtual function allows the derived-class implementation to be called.

For example

#include <iostream>

using namespace std;

class Base
{
public:

    virtual void func()
    {
        cout << "Base class function call" << endl;
    }
};

class Derived : public Base
{
public:

    void func()
    {
        cout << "Derived class function call" << endl;
    }
};

int main()
{
    Base b;
    Derived d;

    b.func();       // Call Base::func()
    d.func();       // Call Derived::func()

    Base* p = &d;   // Base pointer referring to Derived object
    p->func();      // Call Derived::func() at run time
}

The first two calls are straightforward. b.func() calls Base::func(), while d.func() calls Derived::func().

The important part is:

Base* p = &d; p->func();

Although p is a pointer to Base, it refers to a Derived object. Because func() is virtual, C++ selects Derived::func() at run time.

The output is:

Base* p = &d; p->func();

Base class function call
Derived class function call
Derived class function call

The override keyword is optional. It can be used in the derived class to tell the compiler that the function is intended to override a virtual function. If it does not correctly override a base-class virtual function, the compiler reports an error.

Early and Late Binding

A non-virtual function uses early binding. The function call is determined at compile time according to the type of the pointer or reference.

A virtual function uses late binding when called through a base-class pointer or reference. The function is selected at run time according to the type of object being referred to.

For example:

class Base
{
public:

    virtual void virtfunc()
    {
        cout << "Base virtual function" << endl;
    }

    void func()
    {
        cout << "Base non-virtual function" << endl;
    }
};

class Derived : public Base
{
public:

    void virtfunc()
    {
        cout << "Derived virtual function" << endl;
    }

    void func()
    {
        cout << "Derived non-virtual function" << endl;
    }
};

If a base-class pointer refers to a derived-class object:

Base* p = &d; p->func(); p->virtfunc();

the output is:

Base non-virtual function Derived virtual function

The non-virtual func() uses early binding and calls Base::func(). The virtual virtfunc() uses late binding and calls Derived::virtfunc().

Calling the Base-Class Function

The base-class implementation of an overridden function can be explicitly selected using the scope resolution operator (::):

d.Base::func();

This calls Base::func() directly rather than using the virtual function mechanism.

The scope resolution operator is therefore used when a specific class implementation needs to be selected explicitly.

Virtual Destructors

A virtual destructor ensures that when a derived-class object is deleted through a pointer to its base class, the derived-class destructor is called before the base-class destructor.

This is important when a base-class pointer is used to refer to a derived-class object. If the base-class destructor is not virtual and the object is deleted through a base-class pointer, the behaviour is undefined.

For example:

Base* p = new Derived; delete p;

If Base has a virtual destructor, C++ first calls the Derived destructor and then the Base destructor. This ensures that the derived part of the object is properly destroyed before the base part.

A virtual destructor is therefore particularly important when a class is intended to be used as a polymorphic base class.

The following example demonstrates the difference between an object created on the free store and an object created with automatic storage duration:

#include <iostream>

using namespace std;

class Base
{
public:

    Base()
    {
        cout << "Base Constructor" << endl;
    }

    virtual ~Base()
    {
        cout << "Base Destructor" << endl;
    }
};

class Derived : public Base
{
public:

    Derived()
    {
        cout << "Derived Constructor" << endl;
    }

    ~Derived()
    {
        cout << "Derived Destructor" << endl;
    }
};

void DeleteMemory(Base* pBase)
{
    delete pBase;
}

int main()
{
    cout << "Allocating a derived object on the free store:" << endl;

    Derived* pDerived = new Derived;

    cout << "Deleting derived class:" << endl;

    DeleteMemory(pDerived);

    cout << "Instantiating a derived class on the stack:" << endl;

    Derived drv;

    cout << "Automatic destruction as it goes out of scope:" << endl;

    return 0;
}

When the Derived object is created with new, the base-class constructor is called first, followed by the derived-class constructor.

When the object is deleted through the base-class pointer, the virtual destructor causes the destruction to take place in the reverse order:

Derived Destructor Base Destructor

The Derived destructor therefore runs before the Base destructor.

The object drv is different because it has automatic storage duration. It is automatically destroyed when it reaches the end of main(). Its destructors are also called in the correct order:

Derived Destructor Base Destructor

The important point is that inheritance already defines the normal construction and destruction order. The purpose of making the base destructor virtual is to ensure that this destruction sequence is also used when a derived object is deleted through a base-class pointer.

Pure Virtual Functions and Abstract Classes

An abstract class is a class that contains at least one pure virtual function. An abstract class cannot be instantiated directly. It is normally used as a base class that defines an interface or common functionality for derived classes.

virtual void pvf() = 0;

A pure virtual function is declared by placing = 0 after its declaration:

A class containing a pure virtual function is an abstract class. Any derived class must provide an implementation of all inherited pure virtual functions in order to become a concrete class that can be instantiated. If it does not, the derived class remains abstract.

A pure virtual function does not normally have a function body in the base-class declaration. However, C++ does allow a pure virtual function to have a separate definition outside the class. The = 0 still makes the function pure virtual.

#include <iostream>

using namespace std;

class Base
{
public:

    virtual void pvf() = 0;  // Pure virtual function

    Base()
    {
        cout << "Base constructor called" << endl;
    }
};

class Derived : public Base
{
public:

    Derived()
    {
        cout << "Derived constructor called" << endl;
    }

    void pvf() override
    {
        cout << "Derived implementation of pvf()" << endl;
    }
};

int main()
{
    Derived d;

    d.pvf();

    return 0;
}

The Base class is abstract because it contains the pure virtual function pvf(). Therefore, the following would produce a compilation error:

Base b;

However, a Derived object can be created because Derived provides an implementation of pvf().

The output is:

Base constructor called
Derived constructor called
Derived implementation of pvf()

An abstract class can also be used through pointers and references:

Base* p = new Derived; p->pvf(); delete p;

Here, p is a pointer to Base, but it refers to a Derived object. Because pvf() is virtual, the Derived implementation is called.

Characteristics of an Abstract Class

  • An abstract class cannot be instantiated directly, but pointers and references to an abstract class can be created.
  • An abstract class can contain normal member functions as well as pure virtual functions.
  • Abstract classes are commonly used to define an interface and provide common functionality for derived classes.
  • A derived class must implement all inherited pure virtual functions before it can be instantiated. If it does not, the derived class remains abstract.
  • A pure virtual function is declared by using = 0 after the function declaration.

Inheritance

Inheritance allows one class to inherit members from another class. When two or more classes have common characteristics or functionality, inheritance allows these common members to be placed in a base class. A derived class can then inherit the members of the base class and define additional members that are specific to the derived class.

When defining a derived class, a colon is placed after the derived class name, followed by the inheritance access specifier (public, protected, or private) and the name of the base class. For example:

class Derived : public Base

In the worked example below, the calls Derived inherits from class Base. The sequence is as follows

So the sequence is:

  1. Derived dobj; creates a Derived object.
  2. C++ constructs the Base part of that object → Base().
  3. C++ then constructs the Derived part → Derived().

#include <iostream>

using namespace std;
class Base {
public:

    Base() {
        cout << "Base Constructor" << endl;
    }
};

class Derived : public Base {
public:
    Derived() {
        cout << "Derived Constructor" << endl;
    }
};

int main() {
    Derived dobj;
    return 0;
}

Public, Protected and Private Inheritance

When one class inherits from another, the derived class contains a base-class subobject and can access the inherited base-class members according to their access levels and the type of inheritance used.

The access specifiers in the base class determine which members can be accessed by the derived class. The inheritance mode (public, protected, or private) determines how the accessible base-class members are exposed through the derived class.

The three access specifiers are:

  • public – members can be accessed from outside the class, subject to the inheritance mode.
  • private – members cannot be accessed directly from outside the class or from a derived class. They can only be accessed by member functions and friends of the class that declares them.
  • protected – members cannot be accessed directly from outside the class, but they can be accessed by member functions of the class and by derived classes.

For example:

#include <iostream>
using namespace std;
class Base
{
public:
    int publicValue;
protected:
    int protectedValue;
private:
    int privateValue;
};

class Derived : public Base
{
public:

    void function()
    {
        publicValue = 10;       // accessible
        protectedValue = 20;    // accessible
        // privateValue = 30;  // NOT accessible

        cout << "Public value: " << publicValue << endl;
        cout << "Protected value: " << protectedValue << endl;
    }
};

int main()
{
    Derived obj;
    obj.function();
    obj.publicValue=20; //direct changes permitted.
    //obj.protectedValue = 20;    // Not accessible. Direct changes not permitted.
    return 0;
}

Multiple Inheritance

C++ also allows a class to inherit from more than one base class. This is known as multiple inheritance.

Each base class is separated by a comma in the derived-class declaration:

class BaseA { }; class BaseB { }; Class Derived: public BaseA,public BaseB { }

Constructors and Destructors

When an object of a derived class is created, the constructors of its base classes are also called. The base-class constructor is called before the derived-class constructor.

Base-class subobjects are constructed before the derived-class part of the object. Constructors are therefore invoked in order, starting with the most base-level class and progressing down to the most derived class.

When the object is destroyed, the destructors are called in the reverse order. The destructor of the most derived class is called first, followed by the destructors of its base classes.

The following example illustrates the order in which constructors and destructors are executed when inheritance is used. A Derived object is created. Before the Derived constructor executes, the Base constructor is automatically called. The output is therefore:

The output is therefore:

BaseA’s Constructor
BaseB’s Constructor
BaseB’s Destructor
BaseA’s Destructor

#include <iostream>
using namespace std;
class BaseA
{
    public:
        BaseA()
        {
            cout<<"BaseA's Constructor"<<endl;
        }
        ~BaseA()
        {
            cout<<"BaseA's Destructor"<<endl;
        }
};
class BaseB : BaseA
{
    public:
        BaseB()
        {
            cout<<"BaseB's Constructor"<<endl;
        }
        ~BaseB()
        {
            cout<<"BaseB's Destructor"<<endl;
        }
};

int main()
{
    BaseB b;
    return 0;
}

Passing Parameters during Base Class Initialisation

If a base class has a constructor that requires arguments, the derived class must specify which base-class constructor should be called when a derived-class object is created.

The base-class constructor is called from the member-initialiser list of the derived-class constructor.

#include <iostream>
using namespace std;
class Base
{
public:
    Base(int value)
    {
        cout << "Base constructor called with value: "
             << value << endl;
    }
};

class Derived : public Base
{
public:
    Derived() : Base(5)
    {
        cout << "Derived constructor" << endl;
    }
};

int main()
{
    Derived obj;
    return 0;
}

n this example, the Derived constructor uses the member-initialiser list:

Derived() : Base(5)

This calls the Base constructor and passes it the value 5.

When a Derived object is created:

Derived obj;

the Base constructor is called first with the argument 5. The Derived constructor then executes.

The order is therefore:

  1. The Base constructor is called with 5.
  2. The Derived constructor executes.

The base-class constructor must be called before the body of the derived-class constructor executes. If the base class has no default constructor, the derived class must explicitly call an appropriate base-class constructor in its member-initialiser list.

Avoiding Inheritance using Final

In C++11, the final specifier can be used to prevent a class from being inherited from, or to prevent a virtual member function from being overridden.

A class declared as final cannot be used as a base class. Attempting to derive another class from it results in a compiler error:

class Base final { public: void method(); }; // Error: Base cannot be used as a base class class Derived : public Base { }

The final specifier can also be applied to a virtual member function. This prevents derived classes from overriding that particular function:

class Base { public: virtual void method() final; }; // Error: method() cannot be overridden class Derived : public Base { public: void method() override; };

final therefore provides a way to restrict further inheritance or overriding when designing a class hierarchy.

Classes

A class is a user-defined type consisting of related data and functions bundled together as a single entity. The variables and other data stored by a class represent the state of an object, while its member functions provide operations that can work on that data. The variables and functions that make up a class are called its members. A variable declared within a class is called a data member or member variable, and a function declared within a class is called a member function.

Grouping data and the functions that operate on that data within a class is an important part of encapsulation. Encapsulation allows the internal details of a class to be hidden while providing a controlled interface through which the class can be used.

Declaring a Class

A class is defined in C++ using the keyword class followed by the name of the class. The body of the class is enclosed in braces ({ }) and the class definition is terminated by a semicolon.

Defining an Object

An object is an individual instance of a class. Defining a class creates a new type, but does not by itself create an object of that type.

An object can be created by using the class name followed by the name of the object:

box box1;

Here, box is the class type and box1 is an object of that type.

Accessing Class Members

Data members and member functions of an object can be accessed using the dot (.) operator, followed by the name of the member.

For example:

box1.height = 5; box1.boxsize();

Here, height is a data member and boxsize() is a member function of the box1 object.

A Simple Class

The code below creates a class box containing 3 public member variables. Since the variables have been declared public, they can be accessed outside the class definition. Two objects of class box are instantiated and each member variable is initialised with a value. The total volume of the box is calculated by multiplying the individual box variables. 

#include <iostream>
using namespace std;
class box //class definition named box
{
public:
int length;//declare public variable length
int height;//declare public variable height
int width;//declare public variable width
} box1;//instantiate class after class declaration (optional)
int main()
 {
box1.height=5,box1.length=30,box1.width=20;//set values of box1 member variables
cout << "Dimensions of box1 are - " << box1.height*box1.length*box1.width;//output box size
box box2;// instantiate class box 2
box2.height=5,box2.length=30,box2.width=20;//set values of box2 member variables
cout << "\nDimensions of box2 are - " << box2.height*box2.length*box2.width;//output box size
return 

Member Functions

A member function is a function that is declared as a member of a class. Like other functions, member functions can have parameters and can return a value.

A member function can be defined either inside the class definition or outside the class definition.

Outside Class Definition – To define a member function outside the class definition, the scope resolution operator (::) is used with the class name and function name:

int box::boxsize() { return height * length * width; }

Inside Class Definition – A member function defined inside the class definition does not require the scope resolution operator:

int boxsize() { return height * length * width; }

Private, Protected, or Public Members

A class can contain private, protected or public members. By default, all items defined in a class are private.  This means that private members can be accessed only within the functions of the class itself. Public members can be accessed outside the class and protected members are accessible in the class that defines them and in classes that inherit from that class.  Keeping member data private limits access and controls how their values can be changed. Although member variables can be public, it’s considered good programming practice to keep them all private and make them accessible only via the class functions. A function used to retrieve the value of a private member variable is commonly called an accessor or getter, while a function used to change its value is commonly called a mutator or setter.

Constructors

A constructor is a special member of a class that is automatically invoked when an object is created. Constructors are commonly used to initialise the object’s data members.

A constructor has the same name as the class and does not have a return type.

There are several forms of constructor, including default constructors, copy constructors and constructors that take parameters.

Default Constructors

A default constructor is a constructor that can be called without arguments. If the programmer does not declare any constructors and the conditions for an implicitly declared default constructor are met, the compiler can provide one automatically.

Copy Constructors

A copy constructor is a constructor that initialises an object using another object of the same class.

Parameterised Constructors

A parameterized constructor is a constructor that takes one or more parameters. These parameters can be used to initialise the data members of the new object. Using a parameterized constructor allows the programmer to require values when an object is created, although default arguments can also be provided.

Constructor with Initialisation Lists – A constructor can use a member-initialiser list to initialise class data members. The member-initialiser list appears after the constructor’s parameter list and begins with a colon (:). Each member to be initialised is followed by its initial value in parentheses or braces.

The initial value can be supplied by a constructor parameter or can be a fixed value.

box::box(int heightp = 10, int lengthp = 10, int widthp = 10) : height(heightp), length(lengthp), width(widthp) { }

Here, height, length and width are initialised directly using the values supplied to the constructor.

In the example below, the box class is extended to include a constructor that initialises the length, height and width members.

In the worked example below the box class above is extended to include a constructor to  initialise the member variable: length, height and width

#include <iostream>
using namespace std;
class box //class definition named box
{
public:
int boxsize(); 
box(int,int,int);
private:
int length;//declare public variable length
int height;//declare public variable height
int width;//declare public variable width
}; 
//constructor with optional default values 
box::box(int heightp=10,int lengthp=10,int widthp=10):height(heightp),length(lengthp),width(widthp)
{
height=heightp,length=lengthp,width=widthp; 
}
int box::boxsize()
{
 return height*length*width;
}
int main()
 {
box box1;//create object box1 using default values
cout << "Dimensions of box1 are " << box1.boxsize();//output box1 size
box box2(10,20,30);//create object box2 passing user defined value
cout << "\nDimensions of box2 are " << box2.boxsize();//output box2 size
}

Member-initialiser lists are also important because class members are initialised directly rather than being default-initialised and then assigned a value. Some types of members, such as references and const data members, must be initialised using a member-initialiser list.

Destructors

A destructor is a special member of a class that is automatically invoked when an object is destroyed. This normally occurs when an object reaches the end of its lifetime, such as when a local object goes out of scope, when an object created with new is destroyed using delete, or when the program terminates and objects with static storage duration are destroyed.

A destructor has the same name as the class but is preceded by a tilde (~). A destructor does not take parameters and does not have a return type.

If the programmer does not declare a destructor, the compiler can provide one automatically.

Destructors are commonly used to release resources owned by an object, although modern C++ often uses classes such as smart pointers and standard library containers to manage resources automatically.

Friend Functions

A friend functionis allowed to access all private and protected members of the class but is defined outside the class scope.  The declaration of a friend function should be made inside the body of the class using the keyword friend.

In the code section below the friend function output is used to access the private string name.

#include <iostream>
using namespace std;
class UserDetails
{
private:
string name;
public:
UserDetails(): name("john") { }
//friend function
friend string output(UserDetails);
};
// friend function definition
string output(UserDetails f)
{
//accessing private data from non-member function
return f.name;
}
int main()
{
UserDetails f;
cout<<"Distance: "<< output(f);
return 0;
}

Static Class Members

A static member belongs to the class rather than to individual objects of that class. A class can have static data members and static member functions.

A static data member has a single shared value for the class, rather than a separate copy for each object. This single value is shared by all objects of the class.

A static member function can be called using the class name and the scope resolution operator (::) instead of an object. Because a static member function is not associated with a particular object, it does not have access to the this pointer and cannot directly access non-static members.

In the code section below a static member variable is used to keep track of the number of class user objects.

#include <iostream>
 using namespace std;
 class User {
 public:
 static int objectCount;
 // Constructor definition
 User(string n="peter", int a = 32 , string s = "m") {
cout <<"Constructor called." << endl;
name= n;
age = a;
sex = s;
// Increase every time object is created
objectCount++;
}
void userdetails() {
cout << "name-" << name << " age-" << age << " sex-" << sex;
}
static int getCount() {//return objectCount
return objectCount;
}
private:
string name;     
int age;    
string sex;  
} user1;
// Initialise static member of class Box
int User::objectCount = 0;
int main(void) {
//output number of objects
cout << "Object " << User::getCount()<< endl;
user1.userdetails();//output object details
cout << endl;
User user2("mark",32,"m");//create second object
cout << "Object " << User::getCount()<< endl;//output number of object
//output object details
user2.userdetails();
return 0;
}

Const Class Objects and Member Functions

Const Objects – A class object can be declared as const. Once a const object has been initialised, its state cannot be modified. A const object can only call member functions that are declared as const.

For example:

const box box1;

The object’s data cannot subsequently be changed.

Const Member Functions – A member function can be declared as const to indicate that it does not modify the object’s observable state. To declare a member function as const, place the keyword const after the function’s parameter list.

void function() const;

Const member functions can be called on both const and non-const objects. Declaring member functions as const where appropriate helps prevent accidental modification of an object.

Organising Class and Function Definitions

Class definitions are often kept separate from the implementation of a C++ program. A class declaration and its member function declarations are commonly placed in a header file, usually with an .hpp or .h extension.

Member function definitions are commonly placed in a source file with a .cpp extension. A member function defined outside the class uses the class name and scope resolution operator (::) to identify the class to which it belongs.

For example:

int box::boxsize() { return height * length * width; }

Keeping declarations and definitions in separate files can make larger programs easier to organise and maintain.

Anonymous Classes in C++

An anonymous class is a class that is declared without a class name. An object of the class can be created at the same time as the class is defined.

For example:

int box::boxsize() { return height * length * width; }

Here, an unnamed class is defined and an object called box1 is created at the same time.

Because the class has no name, there is no convenient way to declare additional objects of the same class or to refer to the class type elsewhere in the program. For this reason, named classes are normally used when a class needs to be used more than once.

#include <iostream>
using namespace std;
class //anonymous class definition 
{
public:
int length;//declare public variable length
int height;//declare public variable height
int width;//declare public variable width
} box1;//instantiate anonymous class 
int main()
 {
box1.height=5,box1.length=30,box1.width=20;//set values of box1 member variables
cout << "Dimensions of box1 are " << box1.height*box1.length*box1.width;//output box size
return 0;
}

Smart Pointers

A smart pointer is a C++ class that manages a pointer to a dynamically allocated object. Unlike raw pointers, smart pointers can automatically release the dynamically allocated object when it is no longer required. Smart pointers help to manage the lifetime of dynamically allocated objects and reduce the risk of memory leaks.

C++11 introduced three main types of smart pointer, all of which are defined in the <memory> header provided by the Standard Library:

unique_ptr

A unique_ptr is a smart pointer that has exclusive ownership of an object. When the unique_ptr is destroyed, the object it owns is automatically destroyed. The owned object can also be explicitly released by calling reset().

A unique_ptr cannot be copied because there can only be one unique_ptr that owns the object. Ownership can, however, be transferred from one unique_ptr to another using std::move().

The syntax for std::unique_ptr in C++ is:

std::unique_ptr pointerName = std::make_unique(arguments);

std::unique_ptr pointerName = std::make_unique(arguments);

For example:

#include <memory>

int main()
{
    std::unique_ptr<int[]> intarrayPtr =
        std::make_unique<int[]>(100);

    intarrayPtr[0] = 10;

} // Array is automatically deleted here

Use intarrayPtr.reset() if you want to release the memory before the pointer goes out of scope.

shared_ptr

A shared_ptr is a smart pointer that allows multiple shared_ptr objects to share ownership of the same object. The object is automatically destroyed when the last shared_ptr owning it is destroyed or reset.

The syntax for std::shared_ptr in C++ is:

std::shared_ptr pointerName = std::make_shared(arguments);

shared_ptr uses reference counting to keep track of how many shared_ptr objects currently own the same object. When the reference count reaches zero, the object is automatically destroyed.

#include <iostream>
#include <memory>

int main()
{
    std::shared_ptr<int> ptr1 = std::make_shared<int>(15);
    std::cout << "ptr1 value: " << *ptr1 << '\n';
    std::cout << "Owners: " << ptr1.use_count() << '\n';
    {
        std::shared_ptr<int> ptr2 = ptr1;
        std::cout << "ptr2 value: " << *ptr2 << '\n';
        std::cout << "Owners: " << ptr1.use_count() << '\n';
        *ptr2 = 25;
        std::cout << "ptr1 value: " << *ptr1 << '\n';
    }

    std::cout << "Owners after ptr2 goes out of scope: "
              << ptr1.use_count() << '\n';
    return 0;
}

Output
ptr1 value: 15
Owners: 1
ptr2 value: 15
Owners: 2
ptr1 value: 25
Owners after ptr2 goes out of scope: 1

How it works

  1. ptr1 owns an integer containing 15.
  2. ptr2 = ptr1 creates a second shared owner of the same integer.
  3. Changing *ptr2 to 25 also changes the value observed through ptr1, because both pointers refer to the same object.
  4. When ptr2 goes out of scope, its ownership is released and the owner count returns to 1.
  5. When ptr1 goes out of scope, the last owner is released and the integer is automatically destroyed.

Key point: Shared ownership means multiple smart pointers can manage the lifetime of the same object. The object remains alive until the last owning std::shared_ptr releases it.

weak_ptr

A std::weak_ptr is a smart pointer that provides non-owning access to an object managed by a std::shared_ptr. It can be created from a std::shared_ptr and does not increase the shared ownership reference count or extend the object’s lifetime.

A std::weak_ptr can be used to check whether the object still exists by calling expired(). Alternatively, lock() returns a std::shared_ptr if the object still exists, or an empty std::shared_ptr if it has already been destroyed.

This is useful when you need to refer to an object without keeping it alive. It can also help prevent circular references between std::shared_ptr objects.

#include <iostream>
#include <memory>

int main()
{
    std::shared_ptr<int> sharedPtr = std::make_shared<int>(100);
    std::weak_ptr<int> weakPtr = sharedPtr;

    std::cout << "Owners: " << sharedPtr.use_count() << '\n';

    if (auto lockedPtr = weakPtr.lock())
    {
        std::cout << "Value: " << *lockedPtr << '\n';
    }

    sharedPtr.reset();

    if (weakPtr.expired())
    {
        std::cout << "Object no longer exists\n";
    }

    return 0;
}

Output:
Owners: 1
Value: 100
Object no longer exists

Explanation:

  • weakPtr refers to the object managed by sharedPtr without owning it.
  • weakPtr.lock() temporarily obtains shared ownership if the object still exists.
  • sharedPtr.reset() releases sharedPtr’s ownership. Once the temporary lockedPtr has gone out of scope, no shared owners remain, so the integer is destroyed.
  • weakPtr.expired() returns true because the object has been destroyed.

In addition to the smart pointers described above, earlier versions of C++ included std::auto_ptr. This smart pointer was deprecated in C++11 because of its problematic ownership behaviour and was removed from the C++17 standard. Modern C++ programs should use std::unique_ptr instead.

C++ Memory Map and Free Store

The memory that a program uses is typically divided into a few different areas:

• Global namespace – contains global variables
• The free store (heap) – contains dynamically allocated variables 
• Registers – are used for internal housekeeping functions, such as keeping track of the stack and the instruction pointer.
• Code space – contains the program.
• The stack – used for storing function parameters, local variables, and other function-related information are stored.

The free store

Free Store is a large pool of unallocated memory used by the program for dynamic memory allocation during the execution of the program.  Objects allocated on the free store are manipulated indirectly through pointers. Free store memory is allocated through the use of the new operator and deallocated through the delete operator.  The advantage of the free store is that reserved memory is available until its explicitly released. If memory is allocated on the free store while in a function, the memory will still available when the function returns.  The disadvantage of the free store is that that reserved memory remains unavailable until its explicitly released. Failure to free this memory can build up over time resulting in memory leak which can result in performance issues and a possible system crash. 

Allocating Space with the new Keyword

Memory is allocated on the free store by using the new keyword followed by the type of the object that is to be created. This tells the compiler how much memory to set aside.  To request new memory for a variable type int using the following –

int *ptr = NULL; – creates a pointer ptr and assigns NULL
ptr = new int; – allocated space for an int on the heap and assign is address to pointer ptr

or

int *p = new int

Deallocating Space with the delete Keyword

When an area of free store is no longer required, its must freed back to the system because memory allocated with new is not freed automatically. This is done by calling delete on the pointer.  If a pointer variable is pointing to free store memory and the pointer goes out of scope, the memory is not automatically returned to the free store and becomes unavailable. This is called a memory leak. To release memory back to the free store use the keyword delete – 

delete pPointer;

The code section below illustrates the allocating and deleting of a pointer

#include <iostream>
using namespace std;
int main()
{
int * pInt= new int;//create pointer pInt
*pInt=7;//assign value 7
cout << "*pInt: " << *pInt << endl;//output value of pInt
delete pInt;//delete pointer
cout << "*pInt after deleting: " << *pInt << endl;//output pointer value
return 0;
}

If there is insufficient space on the heap the request to allocate memory will fail. The new request will be in the form of an exception of type std::bad_alloc.  If “nothrow” is used with the new operator, it will return a NULL pointer. To add a free store request fail exception to the above code segment –

int *pInt = new(nothrow) int;
if (!pInt)
cout << "allocation of memory failed\n";

Functions

A function is a named, self-contained unit of code that performs a specific task, can receive data through parameters, can return a value to the code that called it, and helps to organise a program into manageable and reusable sections.

Function Prototype

The function prototype declares a function before its definition and details its name, the list of parameters the function accepts, and the return type. The compiler needs to know this information before the function is called. A function defined before main() (forward declaration) does not need a function prototype.

Function calls

A function call transfers control to a function and can supply arguments to it. The parameters in the function declaration specify the data that the function can receive. The arguments supplied in the function call provide the actual values or expressions for those parameters.

Function Parameters

The purpose of parameters is to allow functions to receive arguments. These parameters don’t have to be of the same data type. Any valid C++ data type can be a function parameter, including constants, logical expressions, objects, and other functions that return a value. Data can be passed to functions by value or by reference, and a function can have multiple parameters separated by commas.

Pass by Value – The data associated with the actual parameter is copied into a separate storage location assigned to the function parameter. Any modifications to the function parameter variable inside the called function or method affect only the local parameter.  The parameters passed to a function become local variables within that function, even if they have the same name as variables within the scope of the statement calling the function.

Pass by Reference – Using pass by reference, the function parameter becomes a reference to the original variable supplied as the argument. Changes made through the reference therefore affect the original variable.

Passing large objects by reference can be more efficient than passing them by value because it avoids copying the object. For small types such as int, the performance difference may be negligible.

The code selection below outlines 3 different methods for passing data to a function

#include <iostream> 
using namespace std;
void swapThemByVal(int, int);
void swapThemByRef(int& , int&);
void swapThemByPtr(int *, int *) ;
int main() 
{
int x = 10, y = 20;//declare and initialise variable values
swapThemByVal(x, y); // pass by value
cout << x<< "  " << y << endl;     // displays 10  20
swapThemByRef(x, y);//pass by reference
cout << x << "  " << y << endl;     // displays 20  10
swapThemByPtr(&x, &y);//pass by pointer
cout << x << "  " << y << endl;     // displays 10 20
return 0; 
}
void swapThemByVal(int num1, int num2) 
{
int temp = num1;
num1 = num2;
num2 = temp;
}
void swapThemByRef(int &num1, int &num2) 
{
int temp = num1;
num1 = num2;
num2 = temp;
}
void swapThemByPtr(int *num1, int *num2) 
{
int temp = *num1;
*num1 = *num2;
*num2 = temp;
}

Default Function Parameters

Default function parameters allow a function to be called without specifying an argument for every parameter. When a parameter has a default value in the function declaration, that value is used if the corresponding argument is omitted from the function call.

Important: Parameters with default arguments must appear after all parameters that do not have default arguments.

For example, the following declaration is invalid:

long setvalues(int x, int y, int z = 1, int t);

This is invalid because parameter z has a default argument, but the following parameter t does not.

The correct declaration is:

long setvalues(int x, int y, int t, int z = 1);

Now the function can be called with either four arguments or three arguments:

setvalues(10, 20, 30, 40); // Uses the supplied value of z setvalues(10, 20, 30); // Uses the default value z = 1

Normally when a function is declared in a prototype to receive one or more parameters, the function can only be called with parameters of that data type, however, if the function prototype declares a default value for a parameter the function can be called without that parameter.

Passing an Array of Values to a Function

A built-in C++ array cannot be passed to a function by value as an entire array. When an array is supplied as an argument, the function receives the address of its first element. Any changes in the function will therefore be reflected in the original array. Consequently, the following parameter declarations are functionally equivalent:

C++ does not allow an entire array to be passed as an argument to a function. Pointers to an array are passed as an argument by specifying the array’s name without an index. The argument represents the memory address of the first element of the array. Any changes in the function will therefore be reflected in the original array. To pass a single-dimension array as an argument in a function using one of the following.

All these variants are functionally identical. Each effectively tells the compiler that an integer pointer is to be received.

void myFunction(int *param) - array passed as pointer void myFunction(int param[10])  - array passed a sized array void myFunction(int param[]) - array passed as unsized array

Returning Values from Functions

A function can return a value or return no value by using the void return type. To return a value, the return keyword is followed by an expression whose value is returned to the calling code. The returned value can be assigned to a variable, used in an expression, passed as an argument to another function, or ignored. A function can have multiple return statements.

Auto-Typed Return Values

Another feature added with version C++14 is the automatic deduction of a function’s return type with the auto keyword. This tells the compiler to deduce the return type of the functions by deduction –

auto subtract(int x, int y) { return x — y; }

Functions that rely on automatic return type deduction need to be defined before invoked so the compiler knows a function’s return type where it is used. If a function has multiple return statements, they need to be the same type.

Using Variables with Functions

Local Variables – A variable created in a function is called a local variable because it only exists within the function scope. Ordinary local variables have automatic storage duration. They exist while execution is within their scope and are destroyed when that scope is exited. Local variables are declared like any other variable. The parameters received by the function are also considered local variables. Local variables with automatic storage duration are commonly stored on the stack, although their actual storage is an implementation detail of the compiler.

Global Variables – In C++, variables defined outside all functions, including the main() function, are known as global variables. They can be accessed from different parts of the program, subject to their scope and linkage.

Because a global variable can potentially be accessed and changed by many different parts of a program, using global variables can make it more difficult to track down errors. Limiting the scope of a variable to the part of the program where it is needed reduces the amount of code that needs to be checked when investigating an error. For this reason, the unnecessary use of global variables is generally not considered good programming practice.

The way global variables are stored in memory is implementation-dependent. Non-constant global variables are commonly stored in a data segment or a similar area of memory.

Overloading Functions

Functions with the same name but different parameter lists are called overloaded functions. Overloaded functions can be used in situations where the function called depends on the type of parameters specified in the function call. It is, therefore, possible to create a function that performs a task on different data types without creating unique names for each function. For example – 

int proc(int); int proc(int, int); int proc(long, long);

The proc function above is overloaded with 3 different parameter lists. The 1st and 2nd differ in the number of parameters and the 2nd and 3rd differ in the type of parameter. The parameters the function is called with determine which function will be called. Overloaded functions don’t have to have the same return type, but it is not possible to overload by return type.  Function overloading is also called function polymorphism.

Inline Functions

The inline keyword allows a function to be defined in multiple translation units, provided the definitions are identical. It may also allow the compiler to consider the function for inline expansion, but the compiler is not required to replace a function call with the function body. Small functions are often good candidates for inline expansion

The syntax for defining the function inline is:

inline return-type function-name(parameters) { // code }

Recursion—Functions That Invoke Themselves

A function that calls itself is known as a recursive function. The recursion proceeds until some condition is met which breaks the recursive cycle. The following simple recursive function demonstrates how a countdown procedure calls itself until the exit condition is met.

#include <iostream>
void printFun(int countp) 
{ 
if (countp < 1) //exit function if value of countp is smaller than 1
return; 
else
{ 
printf("Count value = %i\n", countp);
printFun(countp-1); //recursive function calls itself
return; 
} 
} 
int main() 
{ 
int count = 3; 
printFun(count); //call recursive function
}

Controlling Program Flow

Conditional Execution

Conditional execution of code is implemented in C++ using the if, if…else, and switch…case statements.

The if Statement: The if statement selects and executes statement(s) based on a predefined condition. The statement(s) are only executed if the condition evaluates to true. If the condition evaluates to false, execution is skipped and the program control passes to the statement following the if statement.

The syntax of the if statement is

if (condition) { statement 1; statement 2; }

The if-else Statement: The if-else statement causes one of the two possible statement(s) to execute, depending upon the outcome of the predefined condition.

The syntax of the if…else statement is

if (condition) {// code block if condition is true Statement 1; Statement 2; } else {// code block if condition is not true Statement 3; Statement 4; }

The if…else if…else Statement – allows a program to test multiple conditions in sequence. Each condition is evaluated in order, and the statement associated with the first condition that evaluates to true is executed. If none of the conditions is true, the optional else block is executed.

if( expression1 ) // code block if expression 1 is true statement1; else if( expression2 ) // code block if expression 2 is true and expression 1 is false statement2; else // code block if previous conditions are all false statement3;

If expression1 is evaluated to true, statement1 is executed before the program continues. If the expression1 is not true, expression2 is checked and if it evaluates to true, statement2 is executed. If both expression1 and expression2 are false, statement3 is executed. Only one of the three statements is executed.

Conditional Processing Using Switch-Case

The switch-case conditional statement enables a check on a particular expression against a host of possible constant conditions and performs a different action for each of those different values. Each case statement ends with a break statement that causes execution to exit the code block.

The following is the syntax of a switch-case construct:

switch(expression) { case optionA: DoSomething; break; case optionB: DoSomethingElse; break; default: CatchAllWhenExpressionIsNotHandledAbove; break; }

Each case section will often end with a break statement, which causes execution to leave the switch statement. If break is omitted, execution continues into the following case section.

The Conditional Operator ‘? :

The conditional operator is similar to an if-else statement and selects one of the two values or expressions based on a given condition. The conditional operator produces one of two values or expressions depending on the condition. Unlike if…else, it is not used to execute separate blocks of statements.

in the example below the variable highvalue is set to the greater of two given numbers contained in variable num1 and variable num2

int highvalue = (num1 > num2)? num1 : num2;

Looping

Many tasks in a program are accomplished by carrying out a repetitive series of instructions, a fixed number of times or until a specific condition is met. A block of such code is called a loop. Each pass through the loop is called an iteration and the blocks of code are called compound statements.

While Loops

A while loop causes a code block to be executed repeatedly as long as a starting condition remains true. The while keyword is followed by an expression in parentheses. If the expression is true, the statements inside the loop block are executed and executed repeatedly until the expression is false. If the initial condition is not met code inside the block is not executed. In the following code sample, the while loop counts to 10 and exits the loop when the variable i is equal to 10

#include <iostream> 
int main() 
{
int i;
while (i <=10) //test condition
{
std::cout << ++i << "\n";//output value of i
}
}

The while keyword is proceeded by the condition within parentheses. To note, this statement does not end in a semicolon. The statements inside the loop are surrounded by {} braces indicating the start and end of a localised block of code. The loop has the conditional expression i < =10 . The body of code will be executed while the value of i is lower than 10.

Do-While Loops

A do-while loop is a control flow statement that executes a block of code at least once. In contrast to a while loop which starts with a conditional expression before code execution, the do-while loop checks the condition after the block is executed.

#include <iostream> 
int main() 
{
int i = 10;
do
{
std::cout << ++i << "\n";//output value of i
} while (i < 5);//test condition
}

This loop’s conditional statement is only true when i < 5 . Since i begins with a value of 10, this condition is never true however the body of the loop executes once. This occurs because the do-while loop does not evaluate the condition statement until after the loop’s statements are executed. A do-while loop always executes the body at least once.

For Loops

Is an iterative control flow statement that allows code to be executed a specific number of times. The condition is checked at the beginning of each iteration. If it is true, the loop body executes. After the body executes, the increment expression is evaluated before the condition is checked again.

for ( init; condition; increment ) { statement(s); }

The optional init step is executed first, and only once and allows the programmer to declare and initialise any loop control variables. If no initialisation is specified a semicolon must be used.

Following initialisation, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the for loop.

After the body of the for loop executes, the flow of control jumps back up to the increment statement. This process is repeated until the condition becomes false, after which the loop terminates

#include <iostream> 
int main() 
{
for (int i = 0; i < 10; i++)//initialise loop 
{
std::cout << i;//output value of i to screen
}
}

In the code section above, the for loop is declared and the variable i is initialised to 0. The value of i is checked and, if the condition i < 10 is true, the body is executed. If the condition is false, the loop terminates. The variable i is then incremented at the end of the loop and the process is repeated until the condition statement return false and the loop exits.

Leaving any of the three expressions in a for statement blank is permitted. If the condition is omitted, it is treated as always true, so for(;;) creates an infinite loop unless the loop is terminated by another statement.

Advanced for Loops – It is possible to create and run multiple loops within one statement. When the initialisation and action sections contain more than one statement, they are separated by commas.

for (int a = 0, b = 0; a < 10; a++, b++)

This loop has two variable initialisations: a and b, each separated by a comma. The loop’s test section tests whether a < 10 and both integer variables are incremented.

Nested Loops – Loops can be nested with one loop sitting in the body of another. The inner loop will be executed in its entirety for every execution of the outer loop.

for ( init; condition; increment ) { for ( init; condition; increment ) { statement(s); } statement(s); // you can put more statements. }

The Range-Based For Loop –  Introduced in C++11 the range-based loop executes on a predefined range of values such as those contained in an array.

For example, given an array of integers, you would use a range-based for loop to read elements contained in the array.

#include <iostream> 
int main() 
{
int myvalues[] = { 1, 88, 33, -5,13};
for (int aNum : myvalues) // range based for
{
std::cout << "The array elements are " << aNum <<"\n";
}
}

Continue and Breaking

The break statement causes a loop to end immediately, instead of waiting for its condition to be false. When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.

The continue statement skips the remainder of the current iteration and proceeds with the next iteration of the loop. The exact point at which execution resumes depends on the type of loop.

#include <iostream>
using namespace std;
int main () 
{
int a = 10;
do { 
a=a+1; 
if( a == 15) //check if a=15. skip to end of loop
{
continue;    
}   
cout << "value of a: " << a << endl;
} while( a < 20 );
return 0;
}

Usually, programmers expect all code in a loop to be executed when the loop conditions are satisfied. Continue and break modify this behaviour and can result in non-intuitive code. Therefore, continue and break should be used sparingly

The Goto Statement

The goto statement transfers program control directly to a labelled statement. Although it is part of C++, its use is generally discouraged because excessive use can make program flow difficult to understand and maintain.

The syntax for the goto statement is

{
Start: // Called a label
UserCode;
goto Start;
}

Exiting the Program

Under normal circumstances, a C++ program terminates when execution reaches the closing brace of the main() function.

Program termination can, however, be initiated by the program by calling the library functions exit(), abort(), and atexit(). To use these functions, a program must include the header file <cstdlib>

Exit Function

The exit function terminates a C++ program and the argument value supplied to the exit function is returned to the operating system as a return code. A status of zero conventionally indicates successful termination, while a non-zero status indicates some form of failure.The syntax of this function is

void exit ( int status );

In addition, the header file also defines two constants for use as arguments to the exit() function:

Abort Function

The abort function terminates the program immediately bypassing any of the usual run-time termination processing.
The syntax for the atexit function is

void abort();

Atexit Function

The atexit function is used to specify actions that execute before the program terminates. The syntax for the atexit function is

int atexit (void (*func)(void));

The following short program demonstrates how to call a function before closing the program

#include <iostream>
#include <cstdlib>
using namespace std;
void closing()
{
	cout << "Program closure successful";
}
int main()
{
	int x;
	x = atexit(closing);
	if (x != 0)
	{
	cout << "Program Failure";
	exit(1);
	}	
cout << "Program successful" << endl;
return 0;
}

Expressions Statements and Operators

All C++ programs are made up of statements, which are commands that are executed one after another. All statements in C++ end with a semicolon. Each statement takes up one line by convention, but this is not a requirement. Multiple statements can be put on a line as long as each ends with a semicolon. 

To spread a statement over two or more lines, you can do it by adding a backslash ( \ ) to the end of the line

cout << "Hello \ World" << endl; // split to two lines is OK

Whitespace

Whitespace is a term that refers to characters that are used for formatting purposes. In C++, this refers primarily to spaces, tabs, and (sometimes) newlines. The C++ compiler generally ignores whitespace, with a few minor exceptions. Whitespace serves the purpose of making the code more readable to programmers.

Compound Statements

A compound statement is one or more statements enclosed within a bracket{}.

Although every statement in a compound statement must end with a semicolon, the compound statement itself does not end with a semicolon. Variables declared within the statement are local to that compound statement.

Operators

An operator is a symbol that tells the compiler to perform a specific mathematical or logical operation.

Arithmetic Operators

assuming a=2 and b=1

Operator Description Example
+ Adds two operands A + B will give 3
– Subtracts the second operand from the first A – B will give 1
* Multiplies both operands A * B will give 2
/ Divides numerator by de-numerator A / B will give 2
% Modulus Operator and the remainder of after an integer division A % B will give 0
++ increases operator value by one A++ will give 3
— decreases operator value by one A– will give 1

Postfix or Prefix?

In C++ the increment ++ operator increases the value of a variable by 1 and the use of the decrement — operator decreases the value of a variable by 1 however, where the operator is placed has an important effect on how operations are evaluated.

Placing the operator before the operand ie ++var causes the variable value to be increased it returns a value.

Placing the operator after the operand ie var++ causes the variable value to be returned before var is increased.

Relational Operators

assuming a=2 and b=1

Operator Description Example
== returns true (1) if two operands have the same value otherwise returns false (0) (A == B) is not true.
!= returns true (1) if two operands don’t have the same value otherwise returns false (0) (A != B) is true.
> returns true (1) if the left operand is greater than the value of the right operand otherwise returns false (0) (A > B) is true.
< returns true (1) if the left operand is less than the value of the right operand otherwise returns false (0) (A < B) is false.
>= returns true (1) if the left operand is greater than or equal to the value of the right operand otherwise returns false (0) (A >= B) is true.
<= returns true (1) if the left operand is less than or equal to the value of the right operand otherwise returns false (0) (A <= B) is false.

Logical Operators

Assume variable A holds 2 and variable B holds 1, then −

Operator Description Example
&& the logical AND operator evaluates two expressions.If both expressions are true, the logical AND expression is true. A==2 && B==1 result is TRUE
|| The logical OR operator evaluates two expressions. If either is true, the expression is true A==2 || B==1 result is TRUE
! A logical NOT statement reverses a normal expression, returning true if the expression is false and false if the expression is true. !(A==2) result is FALSE

Bitwise Operators

The bitwise operator works on bits and performs bit-by-bit operations. the difference between logical and bitwise operators is that bitwise operators don’t return a boolean result but manipulate individual bits.

The Bitwise operators supported by the C++ language are listed in the following table. Assume variable A holds 50 and variable B holds 25, then −

A = 0011 0010

B = 000 11001

Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 16 which is 0001 0000
| Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 59 which is 0011 1011
^ Binary XOR Operator copies the bit if it is set in one operand but not both. “>(A ^ B) will give 43 which is 00010 1011
~ is a unary operator and has the effect of ‘flipping’ the bits. (~A ) will give -51 which is 1111111111001101 in 2’s complement form.
<< Binary Left Shift Operator. The left operand value is moved left by the number of bits specified by the right operand. A << 1 will give 100 which is 0110 0100
>> Binary Right Shift Operator. The left operand value is moved right by the number of bits specified by the right operand. A >> 2 will give 12 which is 0000 1100

Assignment Operators

Operator Description Example
= Assigns values from right-side operands to left-side operands. C = A + B will assign the value of A + B to C
+= add the value of the expression to the value of the variable to the left of the operator, and assign the result to that variable C += A is equivalent to C = C + A
-= subtract the value of the expression from the value of the variable to the left of the operator, and assign the result to that variable C -= A is equivalent to C = C – A
*= Multiply the right operand with the left operand and assign the result to the left operand. C *= A is equivalent to C = C * A
/= Divide the left operand with the right operand and assign the result to the left operand. C /= A is equivalent to C = C / A
%= Take modulus using two operands and assign the result to the left operand. C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Misc Operators

?—-known as a ternary operator because it requires three operands. Can be used to replace if-else statements

example:y = (x > 10) ? 10 : 20;

Here, y is assigned the value of 10 if x is greater than 10 and 20 if not

. ->(dot and arrow)—- used to reference individual members of classes, structures, and unions.

&(ampersand) —- returns the address of a variable. For example &x; returns location of the variable x in memory

*(asterisk)—- Used to Declare and Dereference a pointer

,(Comma operator)—causes a sequence of operations to be performed. The value of the entire comma expression is the value of the last expression of the comma-separated list. The value of a comma-separated list of expressions is the value of the right-most expression This means that the expression on the right side will become the value of the entire comma-separated expression

example: var = (value1 = 1, value2 = 2, Value1+1);

This statement first assigns the 1 to value1, assigns the 2 to value 2, increments value1 by 1 and finally, assigns the value of value1 to var. The parentheses are necessary because the comma operator has lower precedence than the assignment operator.

Operator’s Precedence in C++

The order in which operators are evaluated in a compound expression is called operator precedence.  In C++, when the compiler encounters an expression, it must analyze the expression and determine how it should be evaluated. To assist with this, all operators are assigned a level of precedence. Those with the highest precedence are evaluated first.

Here, operators with the highest precedence appear at the top of the table, and those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

for example

int myNumber = 20 * 50 + 25 – 25 * 25 << 2;

simplifies to 1000+25-625>>2

simplifies to 400>>2=100

Rank Name Operator
1 Scope resolution ::
2 Member selection, subscription, increment, and decrement . ->
2 Member selection, subscription, increment, and decrement. . ->()++ —
3 sizeof, prefix increment and decrement, complement, and, not, unary minus and plus, address-of and dereference, new, new[], delete, delete[], casting, sizeof() ++ –^ !- +& *()
4 Member selection for a pointer. .* ->*
5 Multiply, divide, modulo * / %
6 Add, subtract + –
7 Shift (shift left, shift right) << = >>=
8 Inequality relational == !=
9 Equality, inequality == !=
10 Bitwise AND &
11 Bitwise exclusive OR ^
12 Bitwise OR |Rank Name Operator |
13 Logical AND && &&
14 Logical OR ||
15 Conditional ?:
16 Assignment operators = *= /= %= += -= <<= >>= &= |= ^=
17 comma ,