Chapter 1 (Introduction To C++)
Chapter 1 (Introduction To C++)
1. Introduction
C++ runs on a variety of platforms, such as Windows, Mac OS, and the various versions of
UNIX.
C++ is a middle-level language, as it encapsulates both high and low level language features.
This language was updated 3 major times in 2011, 2014, and 2017 to C++11, C++14, and
C++17.
POP
Languages like Pascal, C, FORTRAN, and COBOL are called procedure oriented programming
languages. Since in these languages, a programmer uses procedures or functions to perform a
task. When the programmer wants to write a program, he will first divide the task into separate
sub tasks, each of which is expressed as functions/ procedures. This approach is called procedure
oriented approach.
A typical POP structure is shown in above:
In a multi-function program, many important data items are placed as global so that they may be
accessed by all the functions. Each function may have its own local data. Global data are more
vulnerable to an in advent change by a function. In a large program it is very difficult to identify
what data is used by which function. In case we need to revise an external data structure, we
should also revise all the functions that access the data. This provides an opportunity for bugs to
creep in.
Drawback: It does not model real world problems very well, because functions are action
oriented and do not really corresponding to the elements of the problem.
Characterstics of POP:
➢ Emphasis is on doing actions.
➢ Large programs are divided into smaller programs known as functions.
➢ Most of the functions shared global data.
➢ Data move openly around the program from function to function.
➢ Functions transform data from one form to another.
➢ Employs top-down approach in program design.
OOP:
The languages like C++ and Java use classes and object in their programs and are called Object
Oriented Programming languages. The main task is divided into several modules and these are
represented as classes. Each class can perform some tasks for which several methods are written
in a class. This approach is called Object Oriented approach.
OOP allows us to decompose a problem into a number of entities called objects and then builds
data and methods around these entities.
OOP is an approach that provides a way of modularizing programs by creating portioned
memory area for both data and methods that can used as templates for creating copies of such
modules on demand.
That is, an object a considered to be a partitioned area of computer memory that stores data and
set of operations that can access that data. Since the memory partitions are independent, the
objects can be used in a variety of different programs without modifications.
Organization of OOP:
Characterstics OOP:
➢ Emphasis on data.
➢ Programs are divided into what are known as methods.
➢ Data structures are designed such that they characterize the objects.
➢ Methods that operate on the data of an object are tied together.
➢ Data is hidden.
➢ Objects can communicate with each other through methods.
➢ Reusability.
➢ Follows bottom-up approach in program design.
By the help of C++ programming language, we can develop different types of secured and robust
applications:
o Window application
o Client-Server application
o Device drivers
In computing, firmware is a specific class of computer software that provides the low-level
control for a device's specific hardware. ... Some firmware memory devices are permanently
installed and cannot be changed after manufacture. Common reasons for updating firmware
include fixing bugs or adding features to the device.
History of C++ language is interesting to know. Here we are going to discuss brief history of
C++ language.
C++ programming language was developed in 1980 by Bjarne Stroustrup at bell laboratories of
AT&T (American Telephone & Telegraph), located in U.S.A.
C++ is object oriented programming language. It provides a lot of features that are given below.
• Simple: It is a simple language in the sense that programs can be broken down into logical
units and parts, has a rich library support and a variety of data-types.
• Machine Independent but Platform Dependent: A C++ executable is not platform-
independent (compiled programs on Linux won’t run on Windows), however they are
machine independent.
• Mid-level language: It is a mid-level language as we can do both systems-programming
(drivers, kernels, networking etc.) and build large-scale user applications (Media Players,
Photoshop, Game Engines etc.)
• Rich library support: Has a rich library support (Both standard ~ built-in data structures,
algorithms etc.) as well 3rd party libraries (e.g. Boost libraries) for fast and rapid
development.
• Speed of execution: C++ programs excel in execution speed. Since, it is a compiled
language, and also hugely procedural. Newer languages have extra in-built default features
such as garbage-collection, dynamic typing etc. which slow the execution of the program
overall. Since there is no additional processing overhead like this in C++, it is blazing fast.
• Pointer and direct Memory-Access: C++ provides pointer support which aids users to
directly manipulate storage address. This helps in doing low-level programming (where one
might need to have explicit control on the storage of variables).
• Object-Oriented: One of the strongest points of the language which sets it apart from C.
Object-Oriented support helps C++ to make maintainable and extensible programs. i.e.
Large-scale applications can be built. Procedural code becomes difficult to maintain as
code-size grows.
• Compiled Language: C++ is a compiled language, contributing to its speed.
o The core library includes the data types, variables and literals, etc.
o The standard library includes the set of functions manipulating strings, files, etc.
o The Standard Template Library (STL) includes the set of methods manipulating a data
structure.
Before starting the abcd of C++ language, you need to learn how to write, compile and run the
first C++ program.
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Line 1: #include <iostream> is a header file library that lets us work with input and output
objects, such as cout (used in line 5). Header files add functionality to C++ programs.
Line 2: using namespace std means that we can use names for objects and variables from the
standard library.
Line 4: Another thing that always appear in a C++ program, is int main(). This is called
a function. Any code inside its curly brackets {} will be executed.
Line 5: cout (pronounced "see-out") is an object used together with the insertion operator (<<)
to output/print text. In our example it will output "Hello World".
Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }
Remember: The compiler ignores white spaces. However, multiple lines makes the code more
readable.
Line 7: Do not forget to add the closing curly bracket } to actually end the main function.
You might see some C++ programs that runs without the standard namespace library. The using
namespace std line can be omitted and replaced with the std keyword, followed by the :: operator
for some objects:
#include <iostream>
int main() {
std::cout << "Hello World!";
return 0;
}
C++ I/O operation is using the stream concept. Stream is the sequence of bytes or flow of data. It
makes the performance fast.
If bytes flow from main memory to device like printer, display screen, or a network connection,
etc, this is called as output operation.
If bytes flow from device like keyboard, files, or a network connection, etc to main memory, this
is called as input operation.
Let us see the common header files used in C++ programming are:
<iostream> It is used to define the cout, cin and cerr objects, which correspond to standard output
stream, standard input stream and standard error stream, respectively.
<iomanip> It is used to declare services useful for performing formatted I/O, such as setprecision
and setw.
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" <<endl<< “Good Morning;
return 0;
}
You can add as many cout objects as you want. However, note that it does not insert a new line
at the end of the output:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
cout << "I am learning C++";
return 0;
}
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n";
cout << "I am learning C++";
return 0;
}
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n\n";
cout << "I am learning C++";
return 0;
}
The endl is a predefined object of ostream class. It is used to insert a new line characters and
flushes the stream.
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
cout << "I am learning C++";
return 0;
Output:
Hello World!
I am learning C++
The cin is a predefined object of istream class. It is connected with the standard input device,
which is usually a keyboard. The cin is used in conjunction with stream extraction operator (>>)
to read the input from a console.
#include <iostream>
using namespace std;
int main( ) {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your"age is: " << age << endl;
}
It is also possible to use the extraction operator >> on cin to read a string entered by a user:
string firstName;
cout << "Type your first name: ";
cin >> firstName; // get user input from the keyboard
cout << "Your name is: " << firstName;
However, cin considers a space (whitespace, tabs, etc) as a terminating character, which means
that it can only display a single word (even if you type many words):
string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;
That's why, when working with strings, we often use the getline() function to read a line of text.
It takes cin as the first parameter, and the string variable as second:
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;
Consider a situation where there are two individuals named Abhinav in the
same class. To differentiate between them, we might use additional
information such as their area of residence or their parents' names. This helps
us identify which Abhinav we are referring to.
A similar situation can occur in C++ programming. Imagine you have written
a function called info(), and you are using a library that also has a function
named info(). The compiler cannot distinguish between the two functions,
leading to a conflict.
Below is the C++ program illustrating the use of namespace with the same name of function and
variables:
#include <iostream>
using namespace std;
namespace LibraryA {
void info() {
cout << "Info from LibraryA" << endl;
}
}
namespace LibraryB {
void info() {
cout << "Info from LibraryB" << endl;
}
}
int main() {
LibraryA::info(); // Calls info() from LibraryA
LibraryB::info(); // Calls info() from LibraryB
return 0;
}
In the example above, LibraryA and LibraryB are namespaces that each contain a function
named info(). By specifying the namespace, we can call the appropriate info() function without
any ambiguity.
Namespaces are used to avoid name collisions in larger projects where multiple libraries might
be included, each containing functions, classes, or variables with the same names. By defining
these elements within a namespace, you provide a context that uniquely identifies them.
• You can also avoid prepending of namespaces with the using namespace directive. This
directive tells the compiler that the subsequent code is making use of names in the specified
namespace.
• The namespace is thus implied for the following code:
#include <iostream>
using namespace std;
namespace First{
void sayHello(){
cout << "Hello First Namespace" << endl;
}
}
namespace Second{
void sayHello(){
cout << "Hello Second Namespace" << endl;
}
}
using namespace First;
int main () {
sayHello();
return 0;
}
Output:
It is also possible to create two namespace blocks having the same name. The second namespace
block is nothing but actually the continuation of the first namespace. In simpler words, we can
say that both the namespaces are not different but actually the same, which are being defined in
parts.
int main()
{
cout << first::val1 <<"\n";
cout << first::val2 <<"\n";
return 0;
}
Nested Namespaces
Namespaces can be nested within each other to create a hierarchy of namespaces. This is useful
for organizing code into a more structured format.
#include <iostream>
namespace OuterNamespace {
namespace InnerNamespace {
void display() {
std::cout << "Inside InnerNamespace" << std::endl;
}
}
}
int main() {
OuterNamespace::InnerNamespace::display(); // Calls display from InnerNamespace
return 0;
}
#include <iostream>
using namespace std;
return 0;
}
We can create namespace in one file and access contents using another program. This is done in
the following manner.
• We need to create two files. One containing the namespace and all the data members and
member functions we want to use later.
• And the other program can directly call the first program to use all the data members and
member functions in it.
File 1 (file1.h)
// file1.h
namespace foo
{
int value()
{
return 5;
}
}
File 2 (file2.cpp)
// file2.cpp - Not to be executed online
#include <iostream>
#include “file1.h” // Including file1
using namespace std;
int main ()
{
cout << foo::value();
return 0;
}
Here we can see that the namespace is created in file1.h and the value() of that namespace is
getting called in file2.cpp.
Or they might share identifiers with the ones we have created manually in our program.
This is why it is considered a bad practice to include the using namespace std; code in the global
scope.
For example,
#include <iostream>
using namespace std;
string cout() {
return "\n";
}
int main() {
return 0;
}
Here, we have defined our own cout() function while also using the std namespace. This causes a
naming conflict in our program and we get an error when we use cout.
• Namespace Pollution: It brings all identifiers from the namespace into the global scope,
potentially causing name collisions.
• Readability: It can be unclear where a function or variable is coming from, making the
code harder to read and maintain.
• Maintainability: If a new version of a library introduces a new identifier that clashes
with an existing one, it can lead to bugs that are hard to trace.
Instead of using using namespace, it is better to use the namespace resolution operator :: to be
explicit about which namespace an identifier belongs to:
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl; // Explicit std:: prefix
return 0;
}
This approach avoids the pitfalls of namespace pollution and makes the code more readable and
maintainable. By explicitly specifying the namespace, you make it clear which library or context
the identifiers are coming from.