C++ Program Structure

C++ is a very popular programming language. Every C++ program has a general structure that it must follow.

Here is common structure of a C++ program.

C++ Program Structure
C++ Program Structure

Header Section

The header section is used for

  1. Including header files
  2. Declaring global variables
  3. Declaring functions
  4. Defining constants

You can divide C++ functions into two categories – Builtin functions and User-defined functions. Builtin functions are written in a header file that ends with a .h extension. In other words, builtin functions comes with the C++ compiler located in a directory called Include.

User-defined functions are written by programmers. You can write your own codes and store them in the source file for C++ that ends with extension (.cpp).

Syntax to include header file in a C++ program

#include "iostream.h" 

or 

#include <iostream.h>

When you use double quotes the compiler look for the header file in the directory where the C++ program located and then look for file in Include directory that contains all the headers. Otherwise, if we use < ….> , then compiler look for the file only under Include directory.

The header section is a global section because it is outside the main program. You can declare functions (user-defined) with global scope so that all other functions can call it anytime.

void add() ;

int calculate();

You can declare global variables which is used by the main program components such as functions and expressions.

int number;

char name;

You can specify a macro or a numeric constant value in the header section. The value of a numeric constant does not change during the execution of a program.

Syntax for declaring numeric constant

#define MAX 10

#define PI  3.14

The Main Function

The main function is where your program gets executed first. The main function has a default return type of integer in C++. It calls other functions while executing.

void main()
{

            statement 1;

            statement 2;

            ...

            ...

            statement n;

}

The two braces – { and } indicate a block of statements and main() like every other function has a block of statements. The block is the entire C++ program and when it has finished execution, returns an integer value.

If you do not want main to return any value, use the keyword void main() to indicate this.

Other Functions

A user-defined function is a function that performs some task for the user in the program. It is different from built-in functions because user has the control to change the function anytime.

The programmer declares the function in the head section or in the main body of a C program. The declared function has definition that defines what the function does. The best practice is to keep the function definition after main() function. But, it is not necessary.

Putting it all together

The following is an example of C++ program structure.

#include <iostream.h>

#define NUM 100

void main()

{

        int x = 20;

        int sum = 0;

        sum = x + NUM;

        cout << sum << endl;

}

Output

120

C++ Private Member Function & Nested Functions

You have learnt about member functions earlier. We now expand the idea and talk about private member function and nesting of function in C++.

A function declared inside the class’s private section is known as the “private member function”. A private member function is accessible through the only public member function.

Data Members

Data members include members that are mentioned with any of the fundamental types, as well as other types, including pointer, reference, array types, bit fields, and user-defined types.

You can declare a data member the same way as a variable, except those explicit initializers are not allowed inside the class definition. However, a constant static data member of integral or enumeration type may have an explicit initializer.

If an array is declared as a non-static class member, you must specify all of the dimensions of the array.

A class can have members that are of a class type or are pointers or references to a class type. Members that are of a class type must be of a class type that has been mentioned earlier.

An insufficient class type can be used in a member declaration as long as the size of the class is not needed. For example, a member can be implemented that is a pointer to an insufficient class type.

A class X cannot have a member that is of type X, but it can contain pointers to X, references to X, and static objects of X. Member functions of X can take arguments of type X and have a return type of X. 

Member Functions

Member functions are operators and functions that are initialized as members of a class. Member functions do not include operators and functions initialized with the friend specifier.

These are called friends of a class. You can declare a member function as static; this is called a static member function. A member function that is not initialized as static is called a non-static member function.

The definition of a member function is within the scope of its enclosing class. The body of a member function is explored after the class declaration so that members of that class can be used in the member function body, even if the member function definition appears before the declaration of that member in the class member list.

 When the function mul() is called in the following example, the data variables a, b, and c can be used in the body of mul().

Example #1

class x
{
public:
      int mul()             // inline member function mul
      {return a*b*c;};
private:
      int a,b,c;
};

Nesting of member Functions

Whenever we call a member function inside another member function of one class by using dot operator it is known as Nesting of the member function.

 Normally, the member function which is called by another member function is kept private so that it cannot be called directly using the dot operator.

Example #2

#include<iostream.h>
//nested member function

class squarenumb
{
int number;
public:
long square();
void getnumber();
void display();
};

void squarenumb:getnumber()
{
cout<<"Please enter an integer number:";
cin>>number;
}

long squarenumber::square()
{
number=number*number;
return (number);
}

void squarenumb::display()
{
cout<<"Square of the number:"<<square();

}

int main ()
{
squarenumb square;
square.getnumber();
square.display();

return 0;
}

Output:

Please enter an integer number:10
10
Square of the number:100

Summary

The private member function is protection of data wherever necessary, it is for the data protection. Unlike public functions the restricted access ensure that only required members can access the data, which may happen with nested functions.



C++ Objects As Function Arguments

An object can be passed to a function just like we pass a structure to a function. we can pass the object of another class to a function of a different class. We can pass class objects as arguments and return them from a function.

When we want to initialize all data members of an object with another object, we can pass objects and assign the values of a supplied object to the current object. For complex or large projects, we need to use objects as an argument or parameters. So, here’s the question.  

What is an object?

An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is expressed it means an object is created and memory is allocated. 

Declaring Objects: When a class is initialized, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects.

Syntax:

ClassName ObjectName;

What is a class?

A class is a template similar to a blueprint that binds the properties and functions of an entity. You can assign all the entities or objects having similar attributes under a single roof, known as a class. These can further implement the core concepts like encapsulation, data hiding, and abstraction. In C++, a class acts as a data type which can have objects or various instances of the class type. 

  • A Class is a user-defined data type that has data members and member functions.
  • Data members includes data variables and member functions are the functions used to manipulate these variables together these data members and member functions define the properties and behavior of the objects in a Class.

Create a class called “MyCycle”:

class MyCycle {       
  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};

To create an object of MyCycle, specify the class name, and act in accordance by the object name.

To access the class attributes (myNumb and myString), use the dot syntax (.) on the object:

Example #1

Create an object called “myObj” and access the attributes.

class MyCycle {       
  public:             // Access specifier
    int myNumb;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};
int main() {
  MyCycle myObj;  // Create an object of MyCycle
  // Access attributes and set values
  myObj.myNumb = 15; 
  myObj.myString = "Random Info";
  // Print attribute values
  cout << myObj.myNumb << "\n";
  cout << myObj.myString;
  return 0;
}

Output:

15
Random Info

Passing an Object as an argument

The objects of a class can be passed as arguments to member functions as well as non-members functions either by value or by reference. we can pass class objects as arguments and also return them from a function the same way we pass and return other variables. No special keyword or header file is required.

 A copy of the actual object is created inside the function when an object is passed by value. This copy is destroyed when the function terminates. Moreover, any changes made to the copy of the object inside the function are not reflected in the actual object.

 On the other hand, only a reference to that object (not the entire object) is passed to the function in a pass-by-reference. Thus, the changes made to the object within the function are also reflected in the actual object. No special keyword or header file is required to do so.

Whenever an object of a class is passed to a member function of the same class, its data members can be accessed inside the function using the object name and the dot operator. However, the data members of the calling object can be directly accessed inside the function without using the object name and the dot operator.

To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables.

Syntax: 

function_name(object_name);

Returning Object as argument

The returning object will be stored in another variable Object.

Syntax:

object = return object_name;

Example #2

#include <bits/stdc++.h>
using namespace std;
 
class Test{
public:
    int a;
 
    // This function will take
    // object as arguments and
    // return object
    Test add(Test Ta, Test Tb)
    {
        Test Tc;
        Tc.a = Ta.a + Tb.a;
 
        // returning the object
        return Tc;
    }
};
int main()
{
    Example T1, T2, T3;
 
    // Values are initialized
    // for both objects
    T1.a = 50;
    T2.a = 100;
    T3.a = 0;
 
    cout << "Initial Values \n";
    cout << "Value of object 1: " << T1.a
         << ", \nobject 2: " << T2.a
         << ", \nobject 3: " << T3.a
         << "\n";
 
    // Passing object as an argument
    // to function add()
    T3 = T3.add(T1, T2);
 
    // Changed values after
    // passing object as an argument
    cout << "New values \n";
    cout << "Value of object 1: " << T1.a
         << ", \nobject 2: " << T2.a
         << ", \nobject 3: " << T3.a
         << "\n";
 
    return 0;
}

Output:

Initial Values 
Value of object 1: 50, 
object 2: 100, 
object 3: 0
New values 
Value of object 1: 50, 
object 2: 100, 
object 3: 150

In this example, we can see both the things that are how we can pass the objects as well as return them. When the object T3 calls the add function it passes the other two objects namely T1 & T2 as arguments. Inside the function, another object is declared which calculates the sum of all the three variables and returns it to T3. 


This code and the above code are almost the same, the only difference is that this time the add function returns an object whose value is stored in another object of the same class ‘Test’ T3. Here the value of T1 is displayed by object1, the value of T2 by object2, and the value of T3 by object3.

We can also pass an object as an argument within the member function of the class. This is useful, when we want to initialize all data members of an object with another object, we can pass objects and assign the values of a supplied object to the current object.

For complex or large projects, we need to use objects as an argument or parameters.

Example #3

#include <iostream>
using namespace std;

class Decide
{
	private:
	int a;
public:

	void set(int x)
	{
	a = x;
	}

		void sum(Demo ob1, Demo ob2)
		{
			a  = ob1.a + ob2.a;
		}
		void print()
		{
			cout<<"Value of A :  "<<a<<endl;
		}
};
int main()
{
	//object declarations
	Decide d1;
	Decide d2;
	Decide d3;

	//assigning values to the data member of objects
	d1.set(10); 
	d2.set(20); 

	//passing object d1 and d2
	d3.sum(d1,d2);
	
	//printing the values
	d1.print();
	d2.print();
	d3.print();

	return 0;
}

Output:


Value of A:  10
Value of A:  20
Value of A:  30

How do pass objects to functions?

There are four ways of passing objects to functions. Let’s assume you have a class X and want to pass it to a function.

Pass by value

This creates a shallow local copy of the object in the function scope. Things you modify here won’t be reflected in the object passed to it. For example,

Declaration

void fun(X x);
//Calling
X x;
fun(x);

Pass by reference

This passes a reference to the object to the function. Things you modify here will be reflected in the object passed to it. No copy of the object is created. For example,

Declaration

void fun(X &x);
//Calling
X x;
fun(x);

Pass by const reference

This passes a ‘const’ reference to the object to the function. You cannot modify/reassign the object here directly (you can use its methods that do so though). This is useful if you want the function to have only a read-only copy of the object. No copy of the object is created.

Declaration

void fun(X const &x);
//Calling
X x;
fun(x);

Pass by const pointer

This passes a const pointer to the object to the function. You cannot modify/reassign the pointer here.

This is useful if you want the function to have only the address of this object in the pointer. No copy of the object is created.

Declaration

void fun(X const *x);
//Calling
X x;
fun(&x);

Pass by pointer

This passes a pointer to the object to the function. This is similar to passing a reference to the object. No copy of the object is created.

Declaration


void fun(X *x);
//Calling
X x;
fun(&x);

Summary

You have learned about class and objects, how to treat an object as an argument to a function. Not only that , but you also learnt to return the object once the function terminates. It is quite useful to pass objects through function, instead of individual members. But the overhead to send any large object is high when you duplicate the code.

Therefore, we discussed many methods of passing entire object through function with minimum memory. In future articles, we will explore more on this topic.



C++ File Pointer And File Manipulators

What is a file pointer?

 A pointer is used to handle and keep track of the files being accessed. Every file maintains two pointers called get_pointer (in input mode file) and put_pointer (in output mode file), which tells the current position where reading or writing will take place with the use of opening modes and their respective manipulators.

These pointers help attain random access to the file. Like Moving at once to any area withinside the record rather than shifting through it sequentially.

Functions of file handling:

seekg():-

It is used to move the get pointer to the desired location concerning a reference point.

Syntax: file_pointer.seekg (number of bytes ,Reference point); 	
Example: fin.seekg(10,ios::beg); 

tellg():-

tellg() is used to realize which they get pointer is in a file.

Syntax: file_pointer.tellg(); 
Example: int posn = fin.tellg(); 

seekp():-

seekp() is used to move the put pointer to the desired location concerning a reference point.

Syntax: file_pointer.seekp(number of bytes ,Reference point); 
Example: fout.seekp(10,ios::beg); 

tellp():-

tellp()is used to realize which they get pointer is in a file.

Syntax:     file_pointer.tellp(); 
Example:    int posn=fout.tellp(); 

What are the reference points available?

The reference points are:

ios::beg – These are used from the beginning of the file

ios::end – These are used from the end of the file

ios::cur – These are used from the current position in the file.

Files Usage

  • Data Preservation: Storing files in documents allows to hold records even though this system terminates.
  • Easy Data Access: Accessing records will become easy whilst there may be a large number of records and it’s far saved with inside the record, then these files may be accessed the use of the C++ commands.
  • Portability: It will become less difficult to switch records from one pc to any other with no changes.

Operations On Files

 Various operations that can be performed on a file are:  

  • Creation of a new file (fopen with attributes as “a”)
  • Opening an existing file (fopen).
  • Reading from file (fscanf or fgets).
  • Writing to a file (fprintf or fputs).
  • Moving to a specific location in a file (fseek, rewind).
  • Closing a file (fclose).

fstream library

Before diving into each sub-topics, let us first learn about the header file we will be using to gain access to the file handling method. In C++, the fstream library is used to handle files, and it is dealt with with the help of three classes known ofstream, ifstream, and fstream.

ofstream:

This class helps create and write the data to the file obtained from the program’s output.

ifstream:

We use this class to read data from files and also known as the input stream.

fstream:

This class is the combination of both ofstream and ifstream. It provides the ability of creating, writing, and reading a file.

To access the following classes, you must include the fstream as a header file like how we declare iostream in the header.

Example #1

1 #include<iostrea
2 #include<fstream>

fstream library

Before diving into each sub-topics, let us first learn about the header file we will be using to gain access to the file handling method. In C++, the fstream library is used to handle files, and it is dealt with with the help of three classes known ofstream, ifstream, and fstream.

ofstream:

This class helps create and write the data to the file obtained from the program’s output.

ifstream:

We use this class to read data from files and also known as the input stream.

fstream:

This class is the combination of both ofstream and ifstream. It provides the ability of creating, writing, and reading a file.

To access the following classes, you must include the fstream as a header file like how we declare iostream in the header.

After including the header file, there comes a question saying do we need to create the file within the program or else do we need to use an existing file. But this isn’t that difficult to answer because, in C++, we get four different methods to handle files

Opening Modes

What are opening modes?

An opening mode is a setting to control how the stream opens the file. An opening mode can be provided as a second parameter to the constructor of a file stream or its open() member function.

In the “std::ios” namespace we get all modes.

  • “r”- This mode specifies it is open for reading.

If the file does not exist, fopen() returns NULL.

  • “rb”– This mode specifies it is open for reading in binary mode.

 If the file does not exist, fopen() returns NULL.

  • “w”– This mode specifies it is Open for writing. If the file exists, its contents are overwritten.

If the file does not exist, it will be created.

  • “wb”- This mode specifies it is Open for writing in binary mode.

If the file exists, its contents are overwritten. If the file does not exist, it will be created.

  • “a” – This mode specifies it is Open for append. Data is added to the end of the file.

If the file does not exist, it will be created.

  • “ab” – This mode specifies it is Open for append in binary mode. Data is delivered to the end of the file.

If the file does not exist, it will be created.

  • “r+” – This mode specifies it is Open for both reading and writing.

 If the file does not exist, fopen() returns NULL.

  • “rb+” – This mode specifies it is Open for both reading and writing in binary mode.

If the file does not exist, fopen() returns NULL.

  • “w+”–  This mode specifies it is Open for both reading and writing.

If the file exists, its contents are overwritten. If the file does not exist, it will be created.

  • “wb+”- This mode specifies it is open for both reading and writing in binary mode.       

If the file exists, its contents are overwritten. If the file does not exist, it will be created.

  • “a+” – This mode specifies it is open for both reading and appending.

If the file does not exist, it will be created.

  • “ab+” – This mode specifies it is Open for both reading and appending in binary mode.

    If the file does not exist, it will be created.

Example #2: For writing files

#include <iostream>
#include <fstream>
using namespace std;
int main() {
	fstream my_exfile;
	my_exfile.open("my_exfile.txt", ios::out);
	if (!my_exfile) {
		cout << "File not created here!";
	}
	else {
		cout << "File got created!";
		my_exfile << "Example01";
		my_exfile.close();
	}
	return 0;
}

Output:

The file got created!

Closing File

The file (both text and binary) should be closed after reading/writing.

Closing a file is performed using the fclose() function.

fclose(fptr);

Here, fptr is a file pointer associated with the file to be closed.

Example #3: Reading from a File


#include <iostream>
#include <fstream>
using namespace std;
int main() {
	fstream my_exfile;
	my_exfile.open("my_exfile.txt", ios::in);
	if (!my_exfile) {
		cout << "No such file is present";
	}
	else {
		char ch;

		while (1) {
			my_exfile >> ch;
			if (my_exfile.eof())
				break;

			cout << ch;
		}

	}
	my_exfile.close();
	return 0;
}

Output:

Example01
Here, we got the output value which is stored in “example (a)”

Reading and writing to a binary file

Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in the case of binary files.

Writing to a binary file?

To write into a binary file, you need to use the fwrite() function. The functions take four arguments:

address of data to be written on the disk

size of data to be written on the disk

number of such types of data

pointer to the file where you want to write.

Syntax:

fwrite(addressData, sizeData, numbersData, pointerToFile);

Example #4 – Writing a binary file using fwrite()

#include <stdio.h>
#include <stdlib.h>
struct threeDig
{
   int d1, d2, d3;
};
int main()
{
   int n;
   struct threeDig dig;
   FILE *fptr;
   if ((fptr = fopen("C:\\program.bin","wb")) == NULL){
       printf("Error! opening file");

       // Program exits if the file pointer returns NULL.
       exit(1);
   }

   for(n = 1; n < 5; ++n)
   {
      num.n1 = n;
      num.n2 = 5*n;
      num.n3 = 5*n + 1;
      fwrite(&num, sizeof(struct threeDig), 1, fptr); 
   }
   fclose(fptr); 
  
   return 0;
}

In this program, we create a new file program.bin in the C drive.

We declare a structure threeNum with three numbers – n1, n2, and n3, and define it in the main function as num.

Now, inside the for loop, we store the value into the file using fwrite().

The first parameter takes the address of num and the second parameter takes the size of the structure threeNum.

Since we’re only inserting one instance of num, the third parameter is 1. And, the last parameter *fptr points to the file we’re storing the data.

Finally, we close the file.

Manipulators

What are Manipulators?

Manipulators are helping functions that can modify the input/output stream. It does not mean that we change the value of a variable, it only modifies the I/O stream using insertion (<<) and extraction (>>) operators.

Types of Manipulators

There are various types of manipulators:

Manipulators without arguments: The most important manipulators defined by the IOStream library are provided below.

endl: It is defined in ostream. It is used to enter a new line and after entering a new line it flushes (i.e. it forces all the output written on the screen or in the file) the output stream.

ws: It is defined in istream and is used to ignore the whitespaces in the string sequence.

ends: It is also defined in ostream and it inserts a null character into the output stream. It typically works with std::ostrstream, when the associated output buffer needs to be null-terminated to be processed as a C string.

flush: It is also defined in ostream and it flushes the output stream, i.e. it forces all the output written on the screen or in the file. Without flush, the output would be the same, but may not appear in real-time.

Example #5

#include <iostream>
#include <istream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
    istringstream str("           Challenging");
    string line;
    // Ignore all the whitespace in string
    // str before the first word.
    getline(str >> std::ws, line);
  
    // you can also write str>>ws
    // After printing the output it will automatically
    // write a new line in the output stream.
    cout << line << endl;
    // without flush, the output will be the same.
    cout << "only an example" << flush;
    // Use of ends Manipulator
    cout << "\nc";
    // NULL character will be added in the Output

    cout << "a" << ends;
    cout << "t" << endl;
  
    return 0;
}

Output:

Challenging
only an example
cat

The header file iomanip provides a set of functions called manipulators which can be used to manipulate the output formats.

 They provide the same features as the ios(Input-output system) member functions and flags. Some manipulators are more convenient to use than their counterparts in the class(Input-output system) ios. such that, two or more manipulators can be used as a chain in one statement as shown below:

cout << manip1 << manip2 << manip3 << item;
cout << manip1 << item1 << manip2 << item2;

File Pointer & their Manipulation

The read operation from a file involves getting a pointer. It points to a specific location in the file and the reading starts from that location.

Then, the get pointer keeps moving forward which lets us read the entire file. Similarly, we can start writing to a location where the put pointer is currently pointing. The get and put are known as file position pointers and these pointers can be manipulated or repositioned to allow random access to the file

Summary

The C++ file handling is an effiecient tool to manage program output and data in files. In more advanced way to handing data is connecting C++ to a database system such as SQL server and manage data in an efficient way.

This articles talk about flat files manipulations, but you may like to try this examples with Microsoft excel program also.



C++ File Stream Classes

File streams are the libraries which are utilized in programming. These use the iostream preferred standard library because it offers cin and cout strategies which are used for analyzing from the input and writing to the output respectively. 

A file is a collection of associated data stored in a particular area on a disk.

The data transfer can take place in bi-directional ways,

1. Data switch between the console unit and the program.

2. Data switch between the program and a disk file.

What are the file stream classes?

A file stream can be described by using the  ifstream, ofstream, and fstream classes that are contained in the header file fstream.

 The class to be used depends upon the purpose whether the write data or read data operation is to be executed on the file.

By Using iostream standard library, for reading from input and writing to output it provides cin and cout methods.

Operations in File Handling:

  • Creating a file: open()
  • Reading data: read()
  • Writing new data: write()
  • Closing a file: close()

To read and write from a file we are using the standard C++ library known as fstream

Fstream: It is used to create files, writes information to files, and read information from files.

This class provides maintenance for both input and output operations on the files at the same time. It inherits all the member functions of the istream and ostream classes via iostream class. when a file is opened in default mode, it also contains the open() function.

Ifstream: It is used to read information from files. This class supports input operations on the files

 It inherits the features get( ), getline( ), read( ), seekg( ) and tellg( ) from istream class. When the file is opened in default mode, it contains open( ) function.

The functions of ifstream class are :

(i) get()

This function is used to read a single character from the file. The get pointer specifies the character which has to be read from the file. 

(ii) getline()

This function reads a line of text which results up with a newline character. It can be called using cin object as regard to,

cin.getline( line, size)

Where the line is a variable that reads a line of text.

Size is many characters to be read getline() function reads the input until it encounters ‘\n’ or size ⎼1 character is read. It is not saved instead it is replaced by the null character.

(iii) read()

This function scans for a block of data of length specified by an argument ‘n’. This function reads data sequentially. So when the Ending of the function is reached before the whole block is read then the buffer will contain the elements read until the End of the function.

General Syntax

istream & read(char*str, size n);

(iv) seekg()

This function is used to shift the input pointer (i.e., get) to the given location. It belongs to ifstream. It is a file manipulator.

(v) tellg()

This function is used to shift the current position of the input pointer. It belongs to the ifstream class.

Ofstream: It is used to create files and write information to the files.

This class helps output operations on the files. It inherits the functions put(), seekp(), tellp() and write() from ostream class. When the file is opened in default mode, it also includes the open() function.

The functions of ofstream class are mentioned below,

(i) put();

This function is used to write a single character to the file. A stream object specifies to which file the character should be written. This individual will be located at the position specified by the put pointer. This function belongs to fstream class.

(ii) seekp()

This function is used to shift the output pointer that is gi ‘\n’ven location. It belongs to the ofstream class. It is likewise a file manipulator.

(iii) tellp()

This function is used with output streams and returns the current “put” position of the pointer in the stream.

It has no parameters and returns a value of the member type pos_type, which is an integer data type representing the current position of the put stream pointer.

(iv) write()

This function presents a line on the screen. It is used by cout object as follows,

cout.write(line, size)

Where the line is the string to be displayed.

Size is the number of characters to be displayed.

If the size of a string is greater than the line (i.e., text to be displayed) then the write() function stops displaying on encountering a null character but displays beyond the bounds of the line.

File streams are the libraries which are utilized in programming. These use the iostream preferred standard library because it offers cin and cout strategies which are used for analyzing from the input and writing to the output respectively. 

A file is a collection of associated data stored in a particular area on a disk.

The data transfer can take place in bi-directional ways,

1. Data switch between the console unit and the program.

2. Data switch between the program and a disk file.

To read and write from a file we are using the standard C++ library known as fstream

(i) get()

This function is used to read a single character from the file. The get pointer specifies the character which has to be read from the file. 

(ii) getline()

This function reads a line of text which results up with a newline character. It can be called using cin object as regard to,

cin.getline( line, size)

Where the line is a variable that reads a line of text.

Size is many characters to be read getline() function reads the input until it encounters ‘\n’ or size ⎼1 character is read. It is not saved instead it is replaced by the null character.

(iii) read()

This function scans for a block of data of length specified by an argument ‘n’. This function reads data sequentially. So when the Ending of the function is reached before the whole block is read then the buffer will contain the elements read until the End of the function.

General syntax,

istream & read(char*str, size n);

(iv) seekg()

This function is used to shift the input pointer (i.e., get) to the given location. It belongs to ifstream. It is a file manipulator.

(v) tellg()

This function is used to shift the current position of the input pointer. It belongs to the ifstream class.

Ofstream: It is used to create files and write information to the files.

This class helps output operations on the files. It inherits the functions put(), seekp(), tellp() and write() from ostream class. When the file is opened in default mode, it also includes the open() function.

What Are Functions Of ofstream class?

The functions of ofstream class are mentioned below,

(i) put();

This function is used to write a single character to the file. A stream object specifies to which file the character should be written. This individual will be located at the position specified by the put pointer. This function belongs to fstream class.

(ii) seekp()

This function is used to shift the output pointer that is gi ‘\n’ven location. It belongs to the ofstream class. It is likewise a file manipulator.

(iii) tellp()

This function is used with output streams and returns the current “put” position of the pointer in the stream.

It has no parameters and returns a value of the member type pos_type, which is an integer data type representing the current position of the put stream pointer.

(iv) write()

This function presents a line on the screen. It is used by cout object as follows,

cout.write(line, size)

Where the line is the string to be displayed.

Size is the number of characters to be displayed.

If the size of a string is greater than the line (i.e., text to be displayed) then the write() function stops displaying on encountering a null character but displays beyond the bounds of the line.

FileStream Writing to a File

 Example #1

#include <iostream>  
#include <fstream>  
using namespace std;  
int main () {  
 
ofstream filestream("testout.txt");  
 
if (filestream.is_open())  
 
{  
    filestream << “Example for \n";  
    filestream << "Writing to File\n";  
    filestream.close();  
 
}  
 
else cout <<"File does not open";  
 
return 0;  
}   

Output

The content of a text file testout.txt is set with the data:
Example for 
Writing to File 

The content of a text file testout.txt is set with the data:

Example for 

Opening a  File:

A file must be opened before you can read from it or write to it. Either the ofstream or fstream object may be used to open a file for writing and ifstream object is used to open a file for reading purposes only.

You can combine two or more of these values by ORing them together.

 For example: If you want to open a file in write mode and want to truncate it in case that already exists, the following will be the syntax –

ofstream outfile;

outfile.open("file.dat", ios::out | ios::trunc );

Same as we can open a file for reading and writing purposes as follows 

fstream afile;

afile.open(“file.dat”, ios::out | ios::in );

Closing a File:

When a program terminates it automatically removes all the streams, releases all the allocated memory, and closes all the opened files. But it is always a good practice to close all the opened files before program termination.

Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects.

void close();

Example #2 – Closing a File

#include <iostream>  
#include <fstream>  
using namespace std;  
int main () {  
  ofstream myfile;  
  myfile.open ("study.txt");  
  if(myfile.is_open()){  
    cout<<"File opened"<<endl;  
    myfile.close();//file close  
    cout<<"File Closed."<<endl;  
  }  
  else{  
    cout<<"Error in file opening"<<endl;  
  }  
  return 0;  
}

Output:

File opened
File Closed

File Position Pointers

Both istream and ostream provide member functions for repositioning the file-position pointer. These member functions are seekg (“seek get”) for istream and seekp (“seek put”) for ostream.

The argument to seekg and seekp normally is a long integer. A second argument can be specified to indicate the seek direction. The seek direction can be ios::beg (the default) for positioning relative to the beginning of a stream, ios::cur for positioning relative to the current position in a stream, or ios::end for positioning relative to the end of a stream.

The file-position pointer is an integer value that specifies the location in the file as several bytes from the file’s starting location. Some examples of positioning the “get” file-position pointer.

  • position to the nth byte of fileObject (assumes ios::beg)

fileObject.seekg( n );

  • position n bytes forward in fileObject

fileObject.seekg( n, ios::cur );

  • position n bytes back from end of fileObject

fileObject.seekg( n, ios::end );

  • position at end of fileObject

fileObject.seekg( 0, ios::end );

Example #3

fin.seekg(20, ios::beg);   // go to byte no. 20 from beginning of file 

fin.seekg(-5, ios::cur);   // back up 5 bytes from the current position of 

fin.seekg(0, ios::end);      // goes to the end of the file

fin.seekg(-9, ios::end);   // backup 9 bytes from the end of the file

Summary

The file stream has all the built-in functions to create, manipulate files using C++ programming. The article introduced the capabilities of C++ programming. Therefore, in the next article you can learn about file pointers, file manipulation in more detail.



C++ Virtual Functions

In this article, you are going to learn about an important concept in C++ called the virtual functions and pure virtual functions. However, it is recommended that you learn about basics of pointer, classes and derived classes before reading further.

What is Virtual Function?

 A virtual function is a special type of member function that is declared within a base class and is Overridden by a derived class. When you refer to a derived class object using a pointer or a reference to the base class.

 Its name in the base class and the derived classes remains the same Its definition in these classes is indistinct.

We call a virtual function for that object and execute the derived class version of the function.  The virtual function in the derived class is executed through the pointer of the public base class.

How Virtual Functions are declared?

A virtual function is declared by writing the word virtual before function declaration in the base class. The functions with the same name are declared in the derived classes. The use of the word virtual before function declaration in derived classes is optional.

 Once a function is declared virtual in a base class, it becomes virtual in all derived classes; even when the keyword virtual is not written in its definition in the derived classes.

The different versions of a virtual function have derived classes with it.

 In derived classes, the virtual function is reused. A function that is already used is mentioned to override the base class function.

What is Pure Virtual Function?

 A pure virtual function is a virtual function for which we don’t have a fulfillment, we only declare it.

A pure virtual function is declared by assigning 0 while implementing. The virtual function that is only mentioned but not defined in the base class is called the pure virtual function. 

  • The function is made pure virtual in its previous declaration with the keyword virtual and by adding it with equal to 0.
  • A pure virtual function is usually can be  implemented in a base class and must be implemented in a leaf subclass.

You denote that fact by appending the “= 0” to the declaration:

class Abstract Base
{
       virtual void PureVirtualFunction() = 0;
}

Then you cannot declare and instantiate a subclass without it implementing the pure virtual function:

class Derived: public Abstract Base
{
    virtual void PureVirtualFunction() override { }
}

The pure virtual function tells the compiler that the function is pure. The class that contains the pure virtual function exists only to act as a parent of the derived classes. 

This function is implemented in the derived classes.

The base class that has one or more pure virtual functions is called the Abstract Base Class. These classes are designed as a framework or layout for derived classes. 

An abstract base class cannot be identical, that is an object of its type cannot be defined. A pointer to an abstract base class can be defined. 

The derived class that does not have any pure virtual function is called Concrete Derived Class. The pure virtual function of the abstract. Base Class is used in the Concrete Derived Class. The derived classes have their versions of the virtual functions.

The Abstract Base Class is defined at the top of this hierarchy. The Concrete Derived Classes are derived from the Abstract Base Class. The pure virtual functions are declared in the base class. Each derived class contains its version of these pure virtual functions.

Hence, Inferiority is gained within the hierarchy of the class.

What are the Similarities between virtual and pure virtual function?

  • These are the concepts of run-time polymorphism.
  • The syntax declaration of both the functions remains the same all over the program.
  • These functions cannot be global or static.

Differences between virtual function and pure virtual function?

The virtual function and pure virtual function are concepts of run time polymorphism. The main difference between ‘virtual function’ and ‘pure virtual function’ is that ‘virtual function’ has its definition in the base class and also the inheriting derived classes reuse it. 

The pure virtual function has no definition in the base class, and all the inheriting derived classes have to reuse. However, the virtual function is also called dynamic dispatch and run-time dispatch, due to the function called is specified in the run time following the type of the object used

The virtual function’ has its definition in the base class. A ‘Pure Virtual Function’ has no definition in the base class.

A virtual function is created by declaring the function in the base class and adding the keyword ‘virtual’. 

Virtual functions are defined in the base class and overridden in the derived class. Pure Virtual Function is a base class particularly not defined in the base class.

Example of Virtual Function:

#include<iostream.h>
Class bb
{
   Public:
   Virtual void PPP()
   {
   Cout<<” it is the base class ”<<endl;
}
};

Class d1: public bb
{ 
Public:
Void PPP()
{
Cout<<” first derived class”<<endl;
}
};
Class d2: public bb
{
Public:
Void PPP()
{
Cout<<” second derived class”<<endl;
}
};
Main()
{
bb *p;
d1 a;
d2 b;
p=&a;
p->ppp();
p= &b;
p->ppp();
 }

Output:

first derived class
second derived class   

 Explanation of the above program:

In the above program, the keyword “virtual appears only in the definition of the base class bb: it has not been repeated in the derived classes dl & d2 that are derived from the base class bb. Each derived class d1 and d2 and the base class bb have a member function with the same name. i.e. PPP.

The statement “p = &a;“ assigns the address of object bb to the pointer object “p”. When the statement “p->ppp(); is executed for the first time, the pointer object of the base class contains the address of the object of the derived class d1 and the virtual member function of the derived class dl is executed.

Similarly, when the “p->pppo);” statement is executed for the

the second time, the pointer object ‘p’ of the base class contains the address of the derived class d2 and thus the virtual member function of the derived class d2 is executed

in executing the virtual function in c++, the computer selects the function to be called based on the contents of the pointer and not based on the type of the pointer.

Example of Pure Virtual Function:

#include<iostream>
using namespace std;
class B {
  public:
    virtual void s() = 0; // Pure Virtual Function
};

class D:public B {
  public:
    void s() {
     cout << " Example of Virtual Function in Derived class\n";
    }
};
int main() {
  B *b;
  D dobj; // An object of class D
  b = &dobj;// A pointer of type B* pointing to dobj
  b->s();// prints"D::s() called"
}

Output:

Example of Virtual Function in Derived class.  

C++ Reference Variable

C++ language allows you to create a new type of variable called reference variable.

What Is A Reference Variable ?

A variable that store values is called a value variable. The C++ reference variable is an alias for a value variable. It refers to the memory location of the value variable like pointer. Any changes in the value of reference variable can also change the value of variable that its referring to.

Syntax

<type> & <reference variable name> = <value variable name>;

Example#1

int number = 7;
int & prime_num = number;

To declare a reference variable, first declare a value variable. In above example it is the number.

The <type> is the data type of the reference variable, and & is the reference operator (not address of operator) followed by the <reference variable name>.

The above is example of a non const reference variable whose original value changes in the C++ program. What if we want to protect the original variable from any changes in reference variable ?

const Reference Variable

Any changes in the reference variable also change the value of original variable. However, const keyword prevent such changes. A const reference variable is a reference-to-const.

Syntax

const <type> & <reference variable name> = <value variable name>;

Example#2

// constant variable
const int digit = 15;
// reference to constant variable is valid
const int & ref_digit = digit;

Reference to const variable is valid. However, const reference to non const variable and non const reference to a constant is invalid. Consider two example given below.

Example#3

// non const reference to constant value is invalid
int & apples_stock = 34;

Similarly, const reference to non const variable will result in error. A variable which is not constant can change, therefore, reference to such variable is invalid.

Example#4

// non const variable 
double average = 23.87;
// const reference to non const is invalid
const double & ref_average = average; //error

The const reference variable can be Initialized to a different type or to a rvalue. We will discuss more about it in later.

Multiple References

You can declare and Initialize multiple references at the same time.

Example#5

//multiple references 
int a = 100, b = 200; 
int & x = a, & y = b;
int c = 300, & z = c;

Difference Between Pointer And A Reference Variable

A pointer variable and a reference variable work are the same. Both points to memory location of a value variable with a difference that the reference is more efficient and simple than a pointer.

The differences are:

  • Strict binding of reference variable to value variable and does not change, pointers are flexible.
  • Unlike pointers , Null cannot be assigned to reference variable.
  • Reference variables are simple, pointers need lot of dereferencing to access values.
  • You must free pointer memory after use, however, reference variable does not need to free memory.

Initializing And Strict Binding

The reference variable cannot be declared first and then Initialized like pointers because the reference variable is strictly bound to the value variable that it refers to. Once Initialized a reference cannot change. Therefore, a reference must be Initialized as soon as it is declared.

Example#6

int x = 30;
//reference to integer declared
int & y;
// invalid initialization
y = x; 

A pointer variable is declared first and can be Initialized later. Also, a variable is flexible, therefore, you can change the pointer to point to some other variable whenever you like.

Example#7

//declare a variable
float pi = 3.14;
// declare a pointer variable
float x;
// initialize pointer 
x = π 
// print current address
cout << " Address before change " << x << endl; 
// new variable 
float meter = 100.00;
// change pointer reference
x = &meter;
//print current address
cout << " Address after change" << x << endl; 

Output#7

Address before change 0x0045d567
Address after change 0x0063a975

Is it possible to change reference variable like pointer ? The program below answers this question.

Example#8

int num1 = 40;
// Reference to num1
int & mynum1 = num1; 
// New variable
int num2 = 500; 
//Try change reference 
mynum1 = num2; 
// Output memory addresses 
cout << " Address of Num2 = " << &num2 <<endl; 
cout << " Address of Reference mynum1 = " << &mynum1 <<endl; 

Output#8

Address of Num2 = 0x0065d675
Address of Reference mynum1 = 0x00624a765

The address are different because the reference variable mynum1 is still refering to num1. Only value of num2 is assigned to mynum1.

Null Assignment

The NULL is a macro that evaluates to 0 in C programming, but the it is a null pointer means its type casted using (void *)0.

The C and C++ NULL are not same where C++ does not allow (void*)0 definition of NULL. The C++ NULL should be integral constant expression that evaluates to 0. Therefore, a reference cannot be made to constant.

The C++-11, nullptr can be usd instead of NULL which implicitly converts to any pointer type it is assigned to.

A reference cannot be made to nullptr because it is not Initialized and does not point to any object.

Dereferencing Pointers

One of the major difference between pointer and reference variable is use of dereferencing operator. The pointers use dereferencing operator extensively to access values, whereas reference variables are simple to use.

Example#9

// swap using pointers
// function call 
swap(&a, &b);
//function definition
swap(int *a, int *b)
{
  int temp;
  temp = *a; //dereference a
  *a = *b; //dereference b
  *b = temp; 
}
//swap using reference variables x and y
//function call 
swap(x, y);
//function definition
swap(int & x, int & y)
{
   int temp; 
   temp = x; // direct assign x
   x = y ; // direct assign y
   y = temp; 
}

The reference variables are better because no need to send memory address to a function call like pointers. Secondly, no need to dereference those memory address to access values. The reference variable is sending the original values in the function call . 

We will discuss reference variables as function parameter in a separate article. 

Free Pointer Memory

The major drawback of pointer in comparison with reference variable is that a pointer memory must be freed after use because pointers hold separate memory spaces.

This not a problem with reference variable because its is an alias for the original value variable.

Example#10

// reference to function 
int & square (int a ) {
   int c = a * a; 
   int & res = c; 
   return res; 
}
// No need to free function square
int x = square (10); 

Now, consider the same function using pointers.

Example#11

//pointer to function 
int square(int b){
   int *res = b * b;
   return *res; 
}
// Now we must free pointer
int x = square(20);
free(res);

In the next article, we will discuss about the need for const keyword and reference variable as function parameters.



C++ String Basics

C++ strings store textual information. The string variable has a sequence of characters enclosed by double quotes.

In C++ string basics, we cover following topics.

  • Types of strings
  • How to initialise strings ?
  • How to read input strings ?

Types Of Strings

A string is a character array terminated by a null (\0)character. The C++ language allows us to declare two types of strings.

  1. C-style strings
  2. String objects from class string

C-style Strings

The C++ supports C-style strings which is a character array of fixed length. The length of the array is pre-determined or decided when the array is initialised. Each string ends with null character.

Initialise A C-style string

You can declare and initialize C-style string in following ways.

//string declaration
char name[3];    
//string initialisation
name[3] = "Ram";
//string declaration
char state[10]; 
state[10] = {'D','e','l','h','i'};
//declare & initialise at same time
char age[3] = {'2','5'};

When you Initialize the string leave square bracket empty. The size is decided by number of elements inserted into the array.

// string size not defined 
char pincode[] = "2342"; 
// string size not define here also
char pincode[] = {'2','3','5','8'};

The spaces required for a character array can be larger than its requirement.

char animal[30] = "Lion";

The space required for Lion is 4 space. However, there are 30 space available. Therefore, 26 memory space remain unused and wasted.

Important Features of C-style string

  • A null is automatically added at the end of the string.
  • If the string array has extra space than required. Then the memory space is wasted due to internal fragmentation.
  • Length of the array is fixed.
  • Due to its fixed length, the C-style string does not expand more than allocated spaces.

To solve the wastage problem, and make string dynamic.

String Objects From Class string

The C++ string class allows to create variable length string objects. Before you use the string class include the string header file as follows.

#include <string.h>

Depending on the C++ compiler, the file name may differ. Refer to your compiler documentation. For example, Dev C++ 5.11 uses <cstring> .

Initialize String Objects

To initialize string object use one of the following method.

string s = "Hello World!"; // declare and assign value
string p = s;             // assign another string
 
char s[] = "Raju";
string m = string(s);     // convert the character array and assign
string x("Mumbai");       // use the constructor 

Important Features of String Objects

  • The string objects are dynamic and of variable length. The object can shrink or expand because the internal memory is adjusted automatically.
  • If you do not initialize a string, then a string of length 0 is created.
  • The string object may or may not terminate with a null.
  • C++98, C++1 and above offers a wide range of functions to manipulate string objects.

Reading String Inputs

A C++ program receives input from users through input stream (istream). Use one of the member from class istream to receive string inputs.

MethodClass name
cinObject of class istream
get() Public function of class istream
getline()Public function of class istream

cin

The cin is an object of class istream that read input characters from input device such as keyboard. Since , cin is associated with the standard C input stream (studio.h) , it puts the program on wait while user enters the input.

The input is stored in a variable with the help of an extraction operator (>>).

cin >> name;

There is problem reading strings with cin object. Consider the following example.

Example#2

//Program written using Dev C++ 5.11
#include <iostream>
#include <cstring>
#define SIZE 15
using namespace std;
int main ()
{
   char Name [SIZE];
   char State [SIZE];
   
   std::cout << "Enter Name:" << "\n";
   std::cin >> Name;
   std::cout << " Enter State:" << "\n"; 
   std::cin >> State; 
   //Printing output
   std::cout >> "Your name is" >> Name >> std::endl; 
   std::cout >> " Your state is:" >> State >> endl; 
   system ("pause");
   return 0;
}

Output#2

Enter Name: 
John
Enter State:
Doe

The cin stop taking input as soon as a white-space , a tab, or a newline is encountered. Therefore, if user enters ” John doe”. The first part is read and second part remain in the stream. The cin takes it as input for state.

get()

The get () and getline () are two functions that read input characters until a newline character or end of the file is met. The main difference between get() and getline() is that the get() function adds a newline at the end of the string.

The syntax to read a C-style string using get() function is given below.

//Syntax for C-style strings
istream& get (char* s, streamsize n);
istream& get (char* s, streamsize n, char delim);
//example:
char name[10];
cin.get(name, 10);
cin.get(name, 10, '\n');

<span style="color:#cf2e2e" class="tadv-color">s</span> – It is the pointer to character array.

<span style="color:#cf2e2e" class="tadv-color">n</span> – Number of characters to write in the string s including null. It should not be less than 2.

If you want to read only one character use get().

<span style="color:#cf2e2e" class="tadv-color">delim</span> – You may set an explicit delimiting character to end the input. The default is newline (\n).

getline ()

The getline() is also read line from the standard input stream (stdio), but it store the string without null.

Use following syntax to read character array.

// Syntax to read character array
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
//Example
char s[10];
cin.getline(s, 10);
cin.getline(s, 10,'-');

You can receive string object as input using getline ().

// Syntax for String object
istream& getline (istream& is, string& str, char delim);
istream& getline (istream& is, string& str);
//Example
string name;
getline (cin, name);
getline (cin, name, '\n');

<span style="color:#cf2e2e" class="tadv-color">is</span> – stream object from which characters are extracted. Ex. cin.

<span style="color:#cf2e2e" class="tadv-color">str</span> – the string object to store line of text. Any previous entry will be overwritten.

<span style="color:#cf2e2e" class="tadv-color">delim</span> – you can specify an explicit delimiter instead of default newline.

Example#3

//C++ program to receive input using //getline () written using Dev C++ 5.11
#include <iostream>
#include <cstring>
#define SIZE 15
using namespace std;
int main ()
{
    //string declaration
    char name[SIZE];
    string age;
    
    //read input strings
    cout << " Enter Name: " << '\n';
    cin.getline(name, 15);
    cout << " Enter Age : " << '\n';
    getline (cin, age);
    //print output 
    cout << " Your name is " << name << 
    ". Your age is " << age << endl; 
    
    return 0;
}

Output#3

Enter Name: 
John Doe 
Enter Age: 
56
Your name is John Doe. Your age is 56.

References

  • Cplusplus.com. 2020. Istream::Getline – C++ Reference. [online] Available at: <http://www.cplusplus.com/reference/istream/istream/getline/> [Accessed 18 April 2020].
  • Cplusplus.com. 2020. Istream::Getline – C++ Reference. [online] Available at: <http://www.cplusplus.com/reference/istream/istream/getline/> [Accessed 18 April 2020].
  • Sheth, T. (2015). C++ Primer Plus (6th ed., pp. 120-139). Pearson Education India.
  • Bronson, G., & Borse, G. (2010). C++ for engineers and scientists (p. 140). Thomson Course Technology.
  • Balagurusamy, E. (2008). Object oriented programming with C (pp. 428-431). Tata McGraw-Hill.


C++ Integer Data Type

Data types describe the kind of data so that computer can store or manipulate them appropriately. This is the reason to declare a data type in C++ programming.

Data types are also necessary because data items such as numbers are used in expressions. If there is a mismatch, for example – integer and real numbers – in an expression then the computer must be able to resolve it. C++ allows the following data types.

  • Integer
  • Float
  • Double
  • Char

Memory Organization

All data is stored in memory which is organized in bytes. A single byte is of 8 bits.

C++ Data Representation
Figure 1 – C++ Data Representation

The integer data type takes 2 or 4 bytes to store information. This means it takes 16 or 32 bit space.

Integer Data Types

The integers are negative and positive numbers. C++ add modifiers like int,\hspace{3px} short \hspace{3px} int to integers to describe size and range of values of the integer types. The list of modifiers is given below.

  1. int 
  2. long int
  3. short int
  4. signed int
  5. unsigned int

For example

short int = 2 bytes = 16 bits

The integers have both positive and negative values and each bit position takes two values – 0 or 1.

Therefore, its range is -2^{15} to 2^{15}-1

The unsigned \hspace{3px} integer type takes only positive values and the signed \hspace{3px} integer value takes both positive and negative values. All the integer types take 4 bytes of space except the short \hspace{3px} int which takes only 2 bytes of information.

An Example Program

// Program to display the size of integer data types
#include <iostream.h>
int main()
{
        int a = 10;
        short int b = 12;
        long int c = 100;
        unsigned int d = 30;
        signed int e = 32;
   
        cout << sizeof(a) << "Bytes" << endl;
        cout << sizeof(b) << "Bytes" << endl;
        cout << sizeof(c) << "Bytes" << endl;
        cout << sizeof(d) << "Bytes" << endl;
        cout << sizeof(e) << "Bytes" << endl;
        system("pause");
        return 0;
}

Output

4 Bytes
2 Bytes
4 Bytes
4 Bytes
4 Bytes

The sizeof() function takes the variable as an argument and then output the byte size of the variable. The integer variable has a size of 4 bytes on my windows 764 bit machine. The size of the integer variable may be different on a different machine.

C++ Program Structure

C++ is a very popular programming language. Every C++ program has a general structure that it must follow.

Here is common structure of a C++ program.

Header Section

The header section is used for

  1. Including header files
  2. Declaring global variables
  3. Declaring functions
  4. Defining constants

You can divide C++ functions into two categories – Builtin functions and User-defined functions. Built-in functions are written in a header file that ends with a .h extension. In other words, built-in functions comes with the C++ compiler located in a directory called include.

User-defined functions are written by programmers. You can write your own codes and store them in the source file for C++ that ends with extension (.cpp).

Syntax to include header file in a C++ program

#include "iostream.h" 
or 
#include <iostream.h>

When you use double quotes the compiler look for the header file in the directory where the C++ program located and then look for file in include directory that contains all the headers. Otherwise, if we use < \cdots > , then compiler look for the file only under include directory.

The header section is a global section because it is outside the main program. You can declare functions (user-defined) with global scope so that all other functions can call it anytime.

void add() ;
int calculate();

You can declare global variables which is used by the main program components such as functions and expressions.

int number;
char name;

You can specify a macro or a numeric constant value in the header section. The value of a numeric constant does not change during the execution of a program.

Syntax for declaring numeric constant

#define MAX 10
#define PI  3.14

The Main Function

The main function is where your program gets executed first. The main function has a default return type of integer in C++. It calls other functions while executing.

void main()
{
            statement 1;
            statement 2;
            ...
            ...
            statement n;
}

The two braces – \{ and \} indicate a block of statements and main() like every other function has a block of statements. The block is the entire C++ program and when it has finished execution, returns an integer value.

If you do not want main to return any value, use the keyword void main() to indicate this.

Other Functions

A user-defined function is a function that performs some task for the user in the program. It is different from built-in functions because user has the control to change the function anytime.

The programmer declares the function in the head section or in the main body of a C program. The declared function has definition that defines what the function does. The best practice is to keep the function definition after main() function. But, it is not necessary.

Putting it all together

The following is an example of C++ program structure.

#include <iostream.h>
#define NUM 100
void main()
{
        int x = 20;
        int sum = 0;
        sum = x + NUM;
        cout << sum << endl;
}

Output

120