Templates

Templates, Templates, Templates. A template is a way to declassify the type of variable used, e.g. if there was a function to add up two integer values, but you had two double values, then the int function would not function correctly, so there would be a need to function overload the function to allow for the double increment as well. But just envisage that the same function would be required for characters, floats, personally created ones etc, then there would be more functions per type of variable than the actual work done.

A template negates this by allowing any class type passed to the function, as long as the type has the standard increment process defined, it will work with any type.

The syntax for a template is

template <class (template variable name) > (return type) function name (parameters)

Hopefully the code will help in the explanation.

#include <iostream>
 
// the definition is similar to a function, (return type) (function name) (parameters...) instead
// it has a template <class (name of template)>
template <class T> T TemplateAdd(T a, T b)
{
              return (a+b);              // use the internal adding for the variable of type T
              // e.g if defined as a int, then use int add internal, or if a double, use a double etc.
}
 
// template class, same as a function apart from a class 
template<class T> class TemplateClass
{
private:
       T value;       // the internal value
public : 
       TemplateClass(T va)       // set the default internal value in the constructor
       {
              value = va;
       }
 
       T ReturnValue()              // return the default value, all using the template class
       {
              return value;
       }
};
 
int main()
{
       // standard template for a function, pass in two integer values, and also two doubles, it will both work the same
       std::cout << "Adding " << TemplateAdd(3,1) << " " <<  TemplateAdd(3.4, 5.4) << "\n";
 
       // create a int class with the default value of 3
       TemplateClass<int> intTemplate(3);
       std::cout << intTemplate.ReturnValue() << "\n";
 
       // using the same constructor, create a char class with the default value 'b'
       TemplateClass<char> charTemplate('b');
       std::cout << charTemplate.ReturnValue() << "\n";
 
       return 0;
}

Save as templates.cpp, then compile the program. The result displayed will be
Adding 4 8.8
3
b

So using the templates will cut down on the standard function/class types but you do need to be careful to not use any of the non internal class calls within the template, e.g. if you create a new type and do not proved a function to increment the values this will not work.

Just a note that you could add in more different types of templates by
template (return value) (function name) (parameters , e.g. S input1, T input2)

Friends

A friend of a class allow access to the private members of that class, because there are some cases where this is required when the whole of the created class is required to be viewable, e.g. when a private member is not being able to set with the class methods.

To declare a friend within a class, for example to declare a function / class as a friend.

friend int FuncToFriendClass(int a);              // friend to the function.
friend class ClassToClassFriend;              // friend to a class

This will allow the function FuncToFriendClass to gain access to all objects within the class, and the class ClassToClassFriend as well.

The source code

int FuncToFriendClass(int a);              // declare the function, for the class to make a friend.
 
class FriendlyClass 
{
private:
       int private_data;
 
       friend int FuncToFriendClass(int a);              // friend to the function.
       friend class ClassToClassFriend;              // friend to a class
public:
       FriendlyClass()
       {
              private_data = 5;
       }
};
 
int FuncToFriendClass(int a)
{
       FriendlyClass friendClass;                            // the friend to this funciton.
       return friendClass.private_data + a;
}
 
class ClassToClassFriend
{
public:
       int FriendClassPrivateDataMinus(int b)
       {
              FriendlyClass classFriend;
              return classFriend.private_data - b;
       }
};
 
int main()
{
       ClassToClassFriend classFriend;
       std::cout << "Friendly function to class =" << FuncToFriendClass(3) << "\n";
       std::cout << "Friendly class to class = " << classFriend.FriendClassPrivateDataMinus(2) << "\n";
       return 0;
}

If you save that as friend.cpp and then compile, the output will be
Friendly function to class = 8
Friendly class to class = 3

Pointers

Pointers are pointers to memory, the variable that is defined as a pointer still holds the same area in memory as the type of the pointer e.g. char and int are of different size in memory, just do a

cout << sizeof(char) << sizeof(int);

to find out.

The actually pointer holds the address of the variable it is pointing to, e.g.

The value variable

Value = 10, address within the memory for value = 4

The pointer

ValuePointer = 4 (the address of the value), address within the memory = 200

The valuepointer actually equals 4, the memory of the value variable, if you use the * (pointer) then you will get the value pointed to, 10, and if you use the & (address) you will get 200 which is the place in memory where the valuepointer is placed in memory.

For example

int main()
{
int value1 = 10;
int *valp = &value1;       // equals the memory address of value1
 
std::cout << "Value 1 = " << value1 << " address = " << &value1 << "\n";
std::cout << "Value p = " << *valp << " address = " << &valp << " pointed to memory " << valp << "\n";
std::cout << "The value p pointerd to memory is the same as the memory address as value 1\n";
std::cout << "The value p = the pointerd memory value that is assoicated with the value that is in valp (address of memory)\n";
 
(*valp)++;              // correct increament the value that is pointed to by the address held by vapl
std::cout << "Value 1 = " << value1 << " address = " << &value1 << "\n";
std::cout << "Value p = " << *valp << " address = " << &valp << " pointed to memory " << valp << "\n";
 
*valp++;              // incorrect will increament the address that is held valp by sizeof(int) (usually 4)
std::cout << "Value 1 = " << value1 << " address = " << &value1 << "\n";
std::cout << "Value p = " << *valp << " address = " << &valp << " pointed to memory " << valp << "\n";
 
return 0;
}

Local variables

This is a tutorial about variable scope, a variable is a means to store data within the context of the program. For example, if you wish to store a numerical value then you would not store that number in a string, but within a integer or floating point number.

There are different types of variables, integer / string etc, but the scope of a variable is the area in which the variable is defined within block of code that it is situated.

This is some c++ code to demonstrate the difference between local variables and global.

#include <iostream>
 
// global variable
int value1 = 0;
 
void globalVariable()
{
       // output the global variable
       std::cout << "Global " << value1 << "\n";
}
 
int main(void)
{
       int value1 = 1;                     // local function variable
       globalVariable();              // output the global
       std::cout << "Local " << value1 << "\n";       // output the local
 
       // the value1 here is local to the for loop
       for (int value1 = 10; value1 < 15; value1++)
       {
              std::cout << "For loop : " << value1 << "\n";
       }
 
       // output the global and local and notice they have not changed with the very local for loop 
       // with the same variable name.
       globalVariable();
       std::cout << "Local " << value1 << "\n";
       return 0;       
}

the output would be

Global 0
Local 1
For loop : 10
For loop : 11
For loop : 12
For loop : 13
For loop : 14
Global 0
Local 1

To demonstrate that the global /local and looping locals do only work within there area.

Add two numbers

This tutorial will read in two numbers from the console line and output the answer of the two integer values.

The cin refers to the console input, the >> allows the console input value placed into the variable (in this case the val1, val2), NOTE. << would mean output. With using the exception, and the try catch block of code allows for any errors in the conversion of the input into a integer value. Within the printf, there are a few conversion types, the %d means using the corresponding parameter within printf and output a integer value, %s means a string. When I say the corresponding parameter, if there are two %d within the output string, it will display in order the values attached to the printf(...) call. The code

#include <iostream>
#include <exception>
 
//using the namespace std (standard) for the cin -> console input
using namespace std;       
 
int main()
{
       // setup the defaul values.
       int val1 =0, val2 =0;
       try 
       {
              // output to the console
              printf("Please enter number 1 : ");
              // read in the input, if not a integer value, this will
              // cause a error 
              cin >> val1;       
              printf("Please enter number 2 : ");
              cin >> val2;
       }
       catch (exception& e)
       {
              // write out any error exception
              printf("Not a valid input %s\n", e.what());
       }
       // output the answer of the two inputted values.
       printf("Answer : %d\n", (val1 + val2));
       return 0;
}

save this as cppaddtwonumbers.cpp. Once compiled (g++ cppaddtwonumbers.cpp -o cppaddtwonumbers (the -o means to output to the filename else a a.out file name would be created))
Once executed the program, cppaddtwonumbers within Windows, or ./cppaddtwonumbers within Linux/Unix.

The output would be

Please enter number 1 : 23
Please enter number 2 : 41
Answer : 64

Read / Write files

This tutorial will demonstrate how to read in a file and also output the details to another file. The headers
fstream and iostream
basically include details on File-streaming (fstream) and In-Output-Streaming (iostream).

I have attached the code within a zip file with the required input file as well.

The namespace denotes which area are you in, for example : maths:algebra would mean you are doing maths and with the topic of Algebra, within the c/c++ example std::ifstream means that the namespace is std and the function/variable is ifstream.

NOTE: the { } are the begin and end of a code structure, e.g. While begin; do something; end;

#include 
#include
#include

using namespace std;// use the namespace (e.g. instead of putting std::ifstream you just need to put fstream.)

int main(void)
{
char InStr[100];
ifstream InFile("countrys.txt",ios::in);// infile
ofstream OutFile("outcountrys.txt", ios::out);// outfile

while (InFile.getline(InStr,100))// while reading each line within the file
{
printf("%s\n", InStr);// output the read line to the console
OutFile <<

Hello World C C++

You can obtain a few version of a c/c++ compiler from GNU, but if you are using Linux then you should have the compiler already installed.

To display the classic Hello World, save this code below

#include <iostream>
 
int main(void)
{
  std::cout << "Hello world!!";
}

as helloworld.c

Then to compile (if using gcc) into the platform that you are using

#Linux
g++ helloworld.c -o helloworld
#Windows because windows likes .exe
g++ helloworld.c -o helloworld.exe

to run the program, you just need to execute the helloworld file that was created from the above command, if you are using Windows, then you will need to change the line to

The output should be

Hello world!!

Well that is the classic!!