Sunday, December 27, 2015

Chapter 1 - INTRODUCTION TO C++


LET'S LEARN:

  • WHAT IS C++
  • SIMPLE WAY TO LOOK AT OOPs CONCEPT
  • USE OF C++
  • ADVANTAGES OF C++
  • LATEST VERSION
  • HISTORY OF C++ 
  • C++ ENVIRONMENT
  • STRUCTURE OF THE C++ PROGRAM CODE
  • C++ STANDARD LIBRARY
  • C++ STREAMS
  • GETTING STARTED WITH C++ PROGRAM
  • CHAPTER EVALUATION EXERCISE


WHAT IS C++

C++ is an extension (superset) of the C language. It's an open ISO-standardized general-purpose object-oriented programming (OOPs) language. C++ is an effective example of the hybrid language because it is possible to code C++ in a core  level "C style", as well as in an "Object-Oriented style", and most importantly, in a combination of both styles. C++ is also considered to be an intermediate level language, as it can directly handle both high & low-level language features.

cplusplus ajit saigalC++ was developed by Bjarne Stroustrup in 1979 and since then its been constantly upgraded with powerful versions. The language was first called 'C with classes’ as it had all the properties of C language along with an additional concept of 'classes’. However, it was renamed to C++ in 1983. C++ works on cross platforms and so it is ‘operating system independent’.




SIMPLE WAY TO UNDERSTAND OOPs CONCEPT

C++ is an object oriented programming language where almost everything is represented as an Object. The OOP concept in C++ focuses on creating reusable code and follows some basic principles that include: Objects, Class, Encapsulation, Methods, Inheritance, Polymorphism, Data Abstraction.

A Class is a representation of anything that has its own characteristic properties and functional abilities. The Class comprises of:

 

  •   Characteristic Attributes
  •   Functional Behaviors

The Class is just a template (plan) of how something would work out. To put the Class into action/use, we have to first create an Object of that Class and then use it. Let’s now understand this with a very simple example:

If Parrot is a Class, then...

    name, age, type, color are its Characteristic Attributes

    talking, singing, dancing are its Functional Behaviors

Every real Parrot (parrot A, parrot B, parrot C … etc) that we see around us, is a unique Object of the universal Class named Parrot.



WHAT IS THE CONCEPT OF OOPs

Object Oriented Programming or in short OOP, is the style of  programming where we use Objects for performing tasks.

An Object is made from a Class. Each Class contains member-Data and member-Functions (methods). Data is stored in data fields. Methods are functional procedures written as program code. Look at this sample structure of a Class and its Objects.


Before creating an “Object”, we first design/declare a replica of the object. This replica is called the Cass. The “Class” is a declaration of data fields (to store values), the data structure, and related function statements (for performing commonly or repeatedly done tasks). The data and functions belonging to a “Class” are collectively referred to as its member-data or member-function. Member-functions (methods) make use of member-data and perform the declared task. The property of encasing data and functions into a Class is termed as Encapsulation.

An instance of the “Class” is then created so as to perform the tasks declared within it. The real-time instant variable created from a Class is the Object of that Class. The Object executes tasks declared within a Class using the data & functions encapsulated within it.

 

 CLASS

 

A Class is the construct or template declaration for an Object. It is the logical entity of a user defined type or data structure declared with keyword class having data and functions.

 

OBJECT

An Object is the physical entity or instance of a class that is created dynamically to store real time data and execute certain functionality. This process is called instantiation.


You will learn more about Class and Objects later.

WHO INVENTED OBJECT ORIENTED PROGRAMMING

Object Oriented Programming concepts were invented by Kristen Nygaard and Ole-Johan Dahl.


OOP concepts were conceived when Nygaard and Dahl jointly developed the programming language named SIMULA in 1960s while working together at the Norwegian Computing Centre (NCC).

Based on the principles of object oriented programming, SIMULA was directly or indirectly influential in the development of upcoming computer coding languages like C++, VB, Java, Python ...

Graphical user interfaces such as Apple Inc.’s Mac OS and Microsoft Corporation’s Windows OS are founded on the OOP principles.


USE OF C++


C++ is widely used in core level programming for embedded systems, software engineering, constrained devices and large systems programming. It is popular in developing operating systems, browsers, games and all forms of communication systems. It is used in several industries like health care, finance, defense, avionics and aerospace. C++ has greatly influenced later languages like PHP, Java and C# (C-Sharp) because C++ supports multiple programming models that include: procedural, object-oriented, functional etc. 

C++ is highly preferred as the coding language in IoT based sensor-device communication, modern day embedded systems, and cross-platform game engines due to its capabilities of low-level memory manipulation, limited memory usage, less energy consumption and specialized coding for software/hardware needs.

ADVANTAGES OF C++

C++ is a compiled language that guarantees high performance, efficiency and speed. 

C++ is OS independent, and interfaces very well with other languages. 

Programmers can use C++ either as High level language or a Low level language.

C++ Programmer Certifications can be done through Brain Bench Certifications.

A compiled language has a compiler that collectively translates all lines of a program code into machine language and then lists down all the errors (if any) for debugging. Eg: C, C++, C#, Cobol

An interpreted language uses the interpreter to translate each line of the code, one at a time. If an error is found, it has to be corrected first before the next line of code is translated to machine language. Eg: Python, Ruby, Perl, Matlab


LATEST VERSION

C++20 got technically finalized as the latest version and adds more new major features than C++14 or C++17. All the newer versions of C++ includes better features for modern day disruptive technologies in embedded systems, digital communications, resources planning and business processes. Since last few years C++ has been releasing new versions every 3-years. C++23 as the next planned standard looks promising.

HISTORY OF C++

C++ was written by Bjarne Stroustrup at the Bell Labs during 1983-1985. C++ is an extension of C.  Prior to 1983, Bjarne Stroustrup added features to C and formed what he called “C with Classes”. He had combined the Simula’s use of classes and object-oriented features with the power and efficiency of C. The term C++ was first used in 1983 and it was designed for the UNIX system environment. With C++, programmers could improve the quality of code they produced and reusable code was easier to write.

Courtesy: The Newstack @ Bjarne Stroustrup's Plan for Bringing Safety to C++ - The New Stack

Bjarne Stroustrup had studied for the doctoral program at the Computing Laboratory of Cambridge University prior to joining Bell Labs. Now, Bell Labs no longer has that name since part of Bell Labs became AT&T Labs.  The other half became Lucent Bell labs. Prior to C++, C was a programming language developed at Bell Labs in 1969-1973. The UNIX operating system was also being developed at Bell Labs at the same time. C was originally developed for and implemented on the UNIX operating system, on a PDP-11 computer by Dennis Ritchie. He extended the B language by adding types in 1971. He called this NB for New B. Ritchie credited some of his inspiration from the Algol68 language. Ritchie restructured the language and rewrote the compiler and gave his new language the name “C” in 1972. 90% of UNIX was then written in C. The committee that wrote the 1989 ANSI Standard for C had started work on the C Standard project in 1983 after having been established by ANSI in that year. There were quite a number of versions of C at that time and a new Standard was necessary.

C is portable, not tied to any particular hardware or operating system. C combines the elements of high-level languages with the functionality of assembly language and has occasionally been referred to as a middle-level computer language. C makes it easy to adapt software for one type of computer to another. C was a direct descendant of the language B. The language B was developed by Ken Thompson in 1970 for the new UNIX OS. B was a descendant of the language BCPL designed by Martin Richards, a Cambridge University student visiting MIT. C++ is still one of the most powerful languages in use today.


C++ ENVIRONMENT

C++ is commonly used on programming environments called the Integrated Development Environment (IDE) which comes with built in source-code-editor, compiler, debugger etc. There are several IDEs like Borland C++ IDE (for MS DOS and WINDOWS), NetBeans IDE (for Windows, Linux, OS X, Solaris operating systems), Dev C++ (an open-source IDE for Windows), Eclipse CDT (C/C++ Development Tools for Windows, Linux, Mac OS X), Visual Studio Code (for  Windows, macOS, and Linux)… etc. 

An Integrated Development Environment (IDE) is a software application that provides extensive facilities for software development. It consists of a source code editor (where you write the program code), automation tools, and a debugger (for error fixing). Latest IDE’s come with intelligent auto complete feature that assists you while writing the code.


STRUCTURE OF THE C++ PROGRAM CODE

A computer needs to be specifically instructed on what and how a task is to be performed. This is done by coding (writing) a software program.

The program is a set of instructions given to the computer system to perform a specific task. These instructions have to be given exactly in the right order and progressive sequence.

In computer programming, there is an entry point where processor-control is transferred from the operating system to a computer program. The execution of a program can begin at a named point. In C++, the entry point for program execution is often called the main function represented as main() followed by an opening brace ' { ' and closing brace ' } '. It is within these braces that a set of instructions (program code) is written.

Remember that the Operating System controlling your computer, understands only the machine language. It cannot understand C++ program because it’s a high level language. Hence, a C++ Compiler (translator) is used to convert the C++ program code (source code) into machine language code (object code). This object code is then run or executed by the Operating System to give us the desired results. For the compiler to know whether a program translation has successfully been terminated or not, near the exit-point (end) of the program, we may specify a return value as a numeric (int) type parameter. This return value is automatically handed over by the main() to its compiler. The type of such a return value is specified on the left hand side of main function

Eg: int main()

If you don’t need the compiler to know of program termination, you don’t specify a return value at the exit point. But you have to specifically mention that the main() returns no value.

Eg: void main()

Hence the main() basically follows two standard statement formats as shown below:

Format 1: no return value                          Format 2: with integer as return value
void main ()
{
    ……….
    ……….
}




int main ()
{
    ……….
    ……….
return (0);
}



Note: Format 1 is no longer compatible with many of the latest IDE’s and hence, it is advised to follow Format 2 while coding.

C++ STANDARD LIBRARY

C++ standard library is a collection of pre-built programs that can be reused by programmers for specific purposes. These programs come under different headers. For example, input operations are done using the cin object  (of class istreamand output operations are done using the cout object (of class ostream). Both these objects are stored in the input/output header file named iostream (earlier it was iostream.h) from where it can be accessed by the program code. You will be using several header files as you progress further in this course.

Header files contain declaration and definitions of a set of classes and library functions that are used to perform specific operations. Eg. iostream is a header file containing istream/ostream classes from which cin/cout objects are used for input/output operations.

The required C++ library file (header file or namespace based class/object) must be declared before the main() so as to inform the compiler that, during translation of the source-code to object code, there are certain literals (words) used in the program, whose functional meaning can be referred-to in the specified header file. These header files are mentioned by using a pre-processor directive which starts with the # (hash) tag. The pre-processor directive for declaring header file iostream.h is:

#include <iostream.h> (old method)
Or
#include <iostream> (new method)

Some interesting examples of header files which you will learn as we proceed further include: 

1. iomanip is header file for manipulating input/output data with commands like setbase(), endl … etc.
2. cmath header file is for common mathematical functions like finding square root of a number using sqrt(), sine value using sin() … etc.

 

Preprocessor directives are lines of instructions written in a program code that are supposed to be invoked (referred) before actual compilation starts. These directives are preceded by a hash sign (#). These lines are not program statements but are directives for the preprocessor. Eg:

#include <iostream>

#define PI 3.1415




C++ STREAMS

The C++ stream library contains special class objects that manage input/output (i/o) operations as well as error handlingThe stream represents a sequence of data/bytes that “flows into” or “flows out of” a program and are related to files and i/o operations. Eg: cin and cout statements in C++ belong to the iostream header file. Similarly, the open(), close(), read(), write() operations are done using the fstream.

GETTING STARTED WITH C++ PROGRAM

You can type in your C++ Program Code using an Editor. The typed in code has to be compiled by a C++ Compiler. Errors in the code have to be identified and corrected by a Debugger. Finally the program is executed, so as to perform the function it's built for. 

Software applications that provide extensive facilities for writing program codes (source codes) using an editor (mostly with auto complete features), for error fixing using debuggers and for compilation & conversion to executable files (object codes) using compilers are called the Integrated Development Environment (IDE). To write/compile/debug/execute your program code, you can either download an IDE and install it on your system, or can use an online IDE.

Working with OFFLINE IDE: You can download and use an IDE of your choice. The program/source codes in this course, have been developed and tested on Dev-C++ environment. IDE Download link:


https://sourceforge.net/projects/orwelldevcpp/



Working with ONLINE IDE: You can alternatively use an online IDE to type in your program/source code, compile it and run it. Popular online compilers and debuggers can be reviewed here:

·   C++ Shell     : http://cpp.sh/
·   OnlineGDB    : https://www.onlinegdb.com/online_c++_compiler
JDoodle        : https://www.jdoodle.com/online-compiler-c++/

Assuming that you have a C++ IDE, please use the text editor to type in your first C++ program.

PROGRAM 1: Print "Hello World"

(Method 1)

// my first program in C++
#include <iostream>
using namespace std;

int  main ()
{
  cout<< "Hello World";
  return 0;
 }
(Method 2)

// my first program in C++
#include <iostream>

int main()
{
  std::cout << "Hello World";
 }

Save this file with extension .CPP, Compile it and Run the program using appropriate commands as per the IDE (in DEV-C++ press function Key F11 to save + compile + run).

 OUTPUT


Hello World 



We are going to look line by line at the code we have just written:

  • // my first program in C++
This is a comment line. It begins with two slash signs (//) and does not have any effect on the behavior of the program. It can be used to include short explanations or observations within the source code itself. In this case, the line is a brief description of what our program is. You can type in multiple line comment statements within /* and */


Comments

 

Comments are parts of source code that do nothing because the compiler disregards it. They are used to insert notes or descriptions for the programmer. C++ supports two types of comments:

 

1.   // line comment

2.   /* block comment */

 

The line comment discards everything from where the pair of slash signs (//) is found, up to the end of that same line. 

 

The block comment is used to block multiple lines that start from /* and ends with */


  • #include <iostream>
Lines beginning with a pound sign (#) are directives for the preprocessor. They are indications to the compiler on what needs to be preprocessed before compiling. In this case the directive #include <iostream> tells the preprocessor to fetch the “iostream” standard header file before starting to compile the program. This “iostream” file consists of pre-defined input/output functions which will be used in the program.

  • using namespace std;
The compiler is indicated to use the area (namespace) called std where it can find all the functions, variables etc., which will be used in this program code.  Usually, the ‘scope of operation’ of such functions, variables etc are limited within the namespace only. Here, the entire std namespace (very huge) is imported into the current working space and hence, all types of definitions are pulled into the current scopeA “ ; ” ends the statement.

Alternatively in Method2, we have saved space. We have avoided pulling up the entire std namespace by implicitly specifying the namespace to which the identifier belongs using the scope operator (::). The compiler is informed that cout object belongs to the namespace std by a simple statement “std::cout”.

 

What differentiates Namespace from Header File ?

 

The namespace is a logically created area, having a collection of special purpose blocks of code that are part of a wider code library. Eg: The namespace “std” contains the “cout” object, which is part of the iostream header file.

 

Major difference between Namespace and Header File is that, a header file is actual physical storage while the namespace is logical classification.

 

When developing huge applications where we use multiple libraries (header files), the namespace helps prevent different classes with same names being used by different developers.


  • int main ()
main() is the point where all C++ programs start their execution, independent of its location within the source code. The instructions contained within this function’s definition will always be the first one to be executed in any C++ program. It does not matter whether there are other functions with other names defined before or after it. The word main() is followed by a pair of curly braces { } and the program code is written within these curly braces.

int is the return type which indicates to the compiler that this function will return an integer value as the "Exit Status". return 0 is a keyword used at the end of main function to indicate that the program had no error and was a success.

Note: Certain IDE’s ignore programs that  have no int return type and/or no return 0 keyword. Method 2 doesn’t have the return 0 keyword.

  • cout << “Hello World”;
This is a C++ statement that outputs/writes “Hello World” onto the computer screen.

cout represents standard output stream belonging to the iostream header file in C++.

<< is a stream insertion operator that is used for output functions.

semicolon (;) is used to end a statement or an expression. Any number of  semicolon can come in one line.

C++ Statement is a simple or compound expression that can be executed to produce functional effects.

Expression is a sequence of operators & operands specifying computation. Examples are 42, 2 + 2 , a=b+c, "hello, world", function("argument") etc.


Program 2: Demonstrating “comments” and "multiple statements"



/* my second program in C++
   with more comments */
#include <iostream>
int main ()
{
std::cout<< "Hello Good Day - ";     // prints Hello Good Day - 
std::cout<< "I'm a C++ Programmer"; // prints I'm a C++ Programmer
}

Output


Hello Good Day - I’m a C++ Programmer



CHAPTER EVALUATION EXERCISE

A) Choose the most appropriate answer (1 mark)

1. C++ is a _____________ programming language.

(a) functional           (b) procedural         (c) object oriented             (d) imperative

2. _____________ are functional procedures written as program code.

(a) Objects   (b) Class        (c) Data fields          (d) Methods

3. The property of encasing data and functions into a Class is termed as ____________

(a) Encapsulation  (b) Instantiation       (c) Prototyping       (d) Embedding

4. C++ is a ____________ language.

(a) interpreted        (b) compiled                        (c) emulator             (d) vector-oriented

5. IDE has a built in ____________

(a) code editor        (b) compiler             (c) debugger                        (d) all of the above

6. The entry point for C++ program execution is ____________

(a) #include     (b) main()       (c) data declaration      (d) input/output statement

7. ____________ object is a part of ____________ class.

(a) iostream, cout    (b) cout, cin    (c) istream, cin    (d) cout, ostream

8. ____________ is invoked before actual compilation starts.

(a) comment            (b) preprocessor directive           (c) debugging          (d) main()

9. ____________ is a logical area.

(a) Header file     (b)  Standard library     (c) Namespace     (d) block-comment

10. ____________ is used to end a program statement.

(a) semicolon           (b)  curly brace       (c) parenthesis        (d) #

ANSWERS

1) c     2) d     3) a     4) b     5) d     6) b     7) d     8) b     9) c     10) a


B) Fill in the blanks (1 mark)

1. The process of creating physical entity of a class is termed ____________

2. ____________ translates each line of the program code, one by one.

3. Set of instructions that perform a specific task is called the ____________

4. ____________ is a header file used for input/output operations.

5. ____________ header file is for common mathematical functions.

6. ____________ is a stream insertion operator used for output display.

7. std::cout uses the ____________ operator.

8. Single program lines are commented by ____________

9. Object code is saved with extension ____________

10. "return(0)" is used to inform C++ compiler about ____________

ANSWERS

1)        Instantiation            2)        Interpreter               3)        Program
4)        iostream                  5)        cmath                      6)        <<
7)        Scope                      8)        //                            9)        .obj
10)      Program Termination


C) State whether True or False (1 mark)

1. C++ cannot directly handle high and low level languages.
2. Certain IOT communication devices prefer C++ code for efficient memory management and less energy consumption.
3. C++ can be interpreted or compiled.
4. C++ is Operating System dependent.
5. #define is a preprocessor directive.

ANSWERS

1) False          2) True          3) False          4) False          5) True


D) Short answer questions (5 marks)

1. Write a short note on the common use of C++ coding language.
2. What advantages does C++ have ?
3. What is an IDE ?
4. What is a C++ Header File ?
5. Differentiate between Namespace and Header-file.

E) Subjective questions (10 marks)

1. Briefly explain the structure of a C++ Program.
2. Describe C++ standard library.