Friday, 28 December 2018

Discuss C++ part 7

C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell Labs. C++ runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial adopts a simple and practical approach to describe the concepts of C++.

C++ Useful Resources part6

The following resources contain additional information on C++. Please use them to get more in-depth knowledge on this topic.

Useful Links on C++

  • C++ Programming Language Tutorials− C++ Programming Language Tutorials.
  • C++ Programming − This book covers the C++ programming language, its interactions with software design and real life use of the language.
  • Free Country − The Free Country provides free C++ source code and C++ libraries for a number of C++ programming areas including compression, archiving, game programming, the Standard Template Library and GUI programming.
  • C and C++ Users Group − The C and C++ Users Group provides free source code from C++ projects in a variety of programming areas including AI, animation, compilers, databases, debugging, encryption, games, graphics, GUI, language tools, system programming and more.

Useful Books on C++

  • The C++ Programming Language
  • The C++ Programming Language
  • C++ in a Nutshell
  • C++ Programming in Easy Steps
  • C++ Primer Plus
  • Sams Teach Yourself C++ in One Hour a Day

C++ Standard Library part 5

The C++ Standard Library can be categorized into two parts −
  • The Standard Function Library − This library consists of general-purpose,stand-alone functions that are not part of any class. The function library is inherited from C.
  • The Object Oriented Class Library − This is a collection of classes and associated functions.
Standard C++ Library incorporates all the Standard C libraries also, with small additions and changes to support type safety.

The Standard Function Library

The standard function library is divided into the following categories −
  • I/O,
  • String and character handling,
  • Mathematical,
  • Time, date, and localization,
  • Dynamic allocation,
  • Miscellaneous,
  • Wide-character functions,

The Object Oriented Class Library

Standard C++ Object Oriented Library defines an extensive set of classes that provide support for a number of common activities, including I/O, strings, and numeric processing. This library includes the following −
  • The Standard C++ I/O Classes
  • The String Class
  • The Numeric Classes
  • The STL Container Classes
  • The STL Algorithms
  • The STL Function Objects
  • The STL Iterators
  • The STL Allocators
  • The Localization library
  • Exception Handling Classes
  • Miscellaneous Support Library

C++ STL  part 4

Hope you have already understood the concept of C++ Template which we have discussed earlier. The C++ STL (Standard Template Library) is a powerful set of C++ template classes to provide general-purpose classes and functions with templates that implement many popular and commonly used algorithms and data structures like vectors, lists, queues, and stacks.
At the core of the C++ Standard Template Library are following three well-structured components −
Sr.NoComponent & Description
1
Containers
Containers are used to manage collections of objects of a certain kind. There are several different types of containers like deque, list, vector, map etc.
2
Algorithms
Algorithms act on containers. They provide the means by which you will perform initialization, sorting, searching, and transforming of the contents of containers.
3
Iterators
Iterators are used to step through the elements of collections of objects. These collections may be containers or subsets of containers.
We will discuss about all the three C++ STL components in next chapter while discussing C++ Standard Library. For now, keep in mind that all the three components have a rich set of pre-defined functions which help us in doing complicated tasks in very easy fashion.
Let us take the following program that demonstrates the vector container (a C++ Standard Template) which is similar to an array with an exception that it automatically handles its own storage requirements in case it grows −
 Live Demo
#include <iostream>
#include <vector>
using namespace std;
 
int main() {

   // create a vector to store int
   vector<int> vec; 
   int i;

   // display the original size of vec
   cout << "vector size = " << vec.size() << endl;

   // push 5 values into the vector
   for(i = 0; i < 5; i++) {
      vec.push_back(i);
   }

   // display extended size of vec
   cout << "extended vector size = " << vec.size() << endl;

   // access 5 values from the vector
   for(i = 0; i < 5; i++) {
      cout << "value of vec [" << i << "] = " << vec[i] << endl;
   }

   // use iterator to access the values
   vector<int>::iterator v = vec.begin();
   while( v != vec.end()) {
      cout << "value of v = " << *v << endl;
      v++;
   }

   return 0;
}
When the above code is compiled and executed, it produces the following result −
vector size = 0
extended vector size = 5
value of vec [0] = 0
value of vec [1] = 1
value of vec [2] = 2
value of vec [3] = 3
value of vec [4] = 4
value of v = 0
value of v = 1
value of v = 2
value of v = 3
value of v = 4
Here are following points to be noted related to various functions we used in the above example −
  • The push_back( ) member function inserts value at the end of the vector, expanding its size as needed.
  • The size( ) function displays the size of the vector.
  • The function begin( ) returns an iterator to the start of the vector.
  • The function end( ) returns an iterator to the end of the vector.

C++ Object Oriented part3

The prime purpose of C++ programming was to add object orientation to the C programming language, which is in itself one of the most powerful programming languages.
The core of the pure object-oriented programming is to create an object, in code, that has certain properties and methods. While designing C++ modules, we try to see whole world in the form of objects. For example a car is an object which has certain properties such as color, number of doors, and the like. It also has certain methods such as accelerate, brake, and so on.
There are a few principle concepts that form the foundation of object-oriented programming −

Object

This is the basic unit of object oriented programming. That is both data and function that operate on data are bundled as a unit called as object.

Class

When you define a class, you define a blueprint for an object. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object.

Abstraction

Data abstraction refers to, providing only essential information to the outside world and hiding their background details, i.e., to represent the needed information in program without presenting the details.
For example, a database system hides certain details of how data is stored and created and maintained. Similar way, C++ classes provides different methods to the outside world without giving internal detail about those methods and data.

Encapsulation

Encapsulation is placing the data and the functions that work on that data in the same place. While working with procedural languages, it is not always clear which functions work on which variables but object-oriented programming provides you framework to place the data and the relevant functions together in the same object.

Inheritance

One of the most useful aspects of object-oriented programming is code reusability. As the name suggests Inheritance is the process of forming a new class from an existing class that is from the existing class called as base class, new class is formed called as derived class.
This is a very important concept of object-oriented programming since this feature helps to reduce the code size.

Polymorphism

The ability to use an operator or function in different ways in other words giving different meaning or functions to the operators or functions is called polymorphism. Poly refers to many. That is a single function or an operator functioning in many ways different upon the usage is called polymorphism.

Overloading

The concept of overloading is also a branch of polymorphism. When the exiting operator or function is made to operate on new data type, it is said to be overloaded
Quick guide part 2c
x = y;
y = y + 1;
add(x, y);
A block is a set of logically connected statements that are surrounded by opening and closing braces. For example −
{
   cout << "Hello World"; // prints Hello World
   return 0;
}
C++ does not recognize the end of the line as a terminator. For this reason, it does not matter where you put a statement in a line. For example −
x = y;
y = y + 1;
add(x, y);
is the same as
x = y; y = y + 1; add(x, y);

C++ Identifiers

A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9).
C++ does not allow punctuation characters such as @, $, and % within identifiers. C++ is a case-sensitive programming language. Thus, Manpowerand manpower are two different identifiers in C++.
Here are some examples of acceptable identifiers −
mohd       zara    abc   move_name  a_123
myname50   _temp   j     a23b9      retVal

C++ Keywords

The following list shows the reserved words in C++. These reserved words may not be used as constant or variable or any other identifier names.
asmelsenewthis
autoenumoperatorthrow
boolexplicitprivatetrue
breakexportprotectedtry
caseexternpublictypedef
catchfalseregistertypeid
charfloatreinterpret_casttypename
classforreturnunion
constfriendshortunsigned
const_castgotosignedusing
continueifsizeofvirtual
defaultinlinestaticvoid
deleteintstatic_castvolatile
dolongstructwchar_t
doublemutableswitchwhile
dynamic_castnamespacetemplate 

Trigraphs

A few characters have an alternative representation, called a trigraph sequence. A trigraph is a three-character sequence that represents a single character and the sequence always starts with two question marks.
Trigraphs are expanded anywhere they appear, including within string literals and character literals, in comments, and in preprocessor directives.
Following are most frequently used trigraph sequences −
TrigraphReplacement
??=#
??/\
??'^
??([
??)]
??!|
??<{
??>}
??-~
All the compilers do not support trigraphs and they are not advised to be used because of their confusing nature.

Whitespace in C++

A line containing only whitespace, possibly with a comment, is known as a blank line, and C++ compiler totally ignores it.
Whitespace is the term used in C++ to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins.

Statement 1

int age;
In the above statement there must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them.

Statement 2

fruit = apples + oranges;   // Get the total fruit
In the above statement 2, no whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose.
Quick guide part 2b
  • emplate/blueprint that describes the behaviors/states that object of its type support.
  • Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
  • Instance Variables − Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.

C++ Program Structure

Let us look at a simple code that would print the words Hello World.
 Live Demo
#include <iostream>
using namespace std;

// main() is where program execution begins.
int main() {
   cout << "Hello World"; // prints Hello World
   return 0;
}
Let us look at the various parts of the above program −
  • The C++ language defines several headers, which contain information that is either necessary or useful to your program. For this program, the header <iostream> is needed.
  • The line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively recent addition to C++.
  • The next line '// main() is where program execution begins.' is a single-line comment available in C++. Single-line comments begin with // and stop at the end of the line.
  • The line int main() is the main function where program execution begins.
  • The next line cout << "Hello World";causes the message "Hello World" to be displayed on the screen.
  • The next line return 0; terminates main( )function and causes it to return the value 0 to the calling process.

Compile and Execute C++ Program

Let's look at how to save the file, compile and run the program. Please follow the steps given below −
  • Open a text editor and add the code as above.
  • Save the file as: hello.cpp
  • Open a command prompt and go to the directory where you saved the file.
  • Type 'g++ hello.cpp' and press enter to compile your code. If there are no errors in your code the command prompt will take you to the next line and would generate a.out executable file.
  • Now, type 'a.out' to run your program.
  • You will be able to see ' Hello World ' printed on the window.
$ g++ hello.cpp
$ ./a.out
Hello World
Make sure that g++ is in your path and that you are running it in the directory containing file hello.cpp.
You can compile C/C++ programs using makefile. For more details, you can check our 'Makefile Tutorial'.

Semicolons and Blocks in C++

In C++, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity.
For example, following are three different statements −
x = y;
y = y + 1;
add(x, y);
A block is a set of logically connected statements that are surrounded by opening and closing braces. For example −
{
   cout << "Hello World"; // prints Hello World
   return 0;
}
C++ does not recognize the end of the line as a terminator. For this reason, it does not matter where you put a statement in a line. For example −
x = y;
y = y + 1;
add(x, y);
is the same as
x = y; y = y + 1; add(x, y);

C++ Identifiers

A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9).
C++ does not allow punctuation characters such as @, $, and % within identifiers. C++ is a case-sensitive programming language. Thus, Manpowerand manpower are two different identifiers in C++.
Here are some examples of acceptable identifiers −
mohd       zara    abc   move_name  a_123
myname50   _temp   j     a23b9      retVal

Featured Post