“LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”

Knowledge flow- A mobile learning platform provides apps, eBooks and video tutorials

Knowledge flow brings you learning eBook of C++ Programming Language. This eBook is for all information technology and computer science students and professionals across the world.

Follow us on

Facebook

Google plus

Twitter

For more information visit us at

Knowledgeflow.in

knowledgeflowapps.blogspot.in

Thank you for using Knowledge flow eBooks

C++ PROGRAMMING LANGUAGE

1. Introduction of C++

2. General structure

3. Input Output Streams 

4. Operators 

5. Variables and Data types 

6. Modifiers 

7. Control structures 

8. Functions 

9. Classes 

10. Objects 

11. Member functions 

12. Inheritance 

13. Polymorphism 

14. More eBooks and Apps

Disclaimer

This eBook contents is for informational and study purposes only. The Knowledge flow makes no claims, promises, or guarantees about the accuracy, completeness, or adequacy of the contents of this eBook and no legal liability or other responsibility is accepted by Knowledge flow for any errors, omissions, or statements on this eBook.

Introduction of C++

C++ is an excellent featured of programming language that based on concept of object oriented programming, developed by Bjarne Stroustrup in the early 1980’s at AT&T Bell Labs in USA.

C++ was originally called by name C with classes and renamed C++ in 1983.

The name C++ comes from the C with increment operator ++ that denoted the enhanced version of C.

The language C++ adding new features such classes, objects, polymorphism, operators, member functions, multiple inheritances.

Structure of a C++ program

Include files

Class declaration

Member functions definitions

Main function program

A simple Example of a C++ program

#include //include header file
using namespace std;
int main()
{ cout<<”Hello world”\n; // C++ Statement
return 0;
}

New version of header files

<iostream>

<cmath>

<cstdio>

<cfloat>

<cstring>

<fstream>

<cassert>

General structure

Header comments
Includes header file
Function {
Statements
}

Example

// My First Program
#include <iostream.h>
using namespace std;
int main ()
{
cout << "Hello world";
return 0;
}

// My First Program

This is the comment line that starts with two slash signs // and do not have any effect on the behaviour of the program.

#include <iostream.h>

Input output stream header file. The line starts with # are directives for the preprocessor. It is specially designed to perform input and output operations on character, files or strings.

using namespace std;

It is a container is used to allow us to group of classes, functions and objects into one group. When we use using

namespace std;

It’s instructing compiler to use the standard C++ library.

int main ()

The main function is the place where all C++ starts program execution.

cout/cin

It is the parts of C++ statement. cout standard output to print the message to the screen and cin standard input to read the input from the keyboard.

return 0;

It is the ending of the main function. return 0; represent the program treat as without errors during execution. It is usually use to end of C++ program.

Input Output streams

In C++ standard libraries provide a set of input/output capabilities occurs in streams, which are flow of bytes.

If bytes flow from a device likes keyboard to main memory, it is called input operation and bytes flow from main memory to a device like a display screen called output operation.

There are several header files in C++ library.

<ios>

It contains ios_base and basic_ios classes and the associated stream buffer.

<istream>

It implements formatted input.

<ostream>

It implements formatted output.

<iostream>

It implements formatted input and output.

<fstream>

It contains basic_fstream, basic_ifstream and basic_ofstream and class templates which implement formatted input and output on file streams.

<sstream>

It contains the basic_stringstream, basic_istringstream and basic_ostringstream and class templates which implement formatted input and output on string-based streams.

Input output functions

Input function

To take input from user we must have to use “cin” as input.

Syntax

cin>> variable

Output function

To take input from user we must have to use “cin” as input.

Syntax

cout<< “Message”;

Operators

Operators are symbol that instruct the compiler to perform specific mathematical or logical manipulations. C++ has rich set of operators. In C++ there are following types of operators.

Arithmetic Operators

Logical Operators

Relational Operators

Assignment Operators

Bitwise Operators

Arithmetic Operators

In C++ there are following arithmetic operators supported.

+ operator- It add two operands.

- operator- It subtracts second operands from first.

* operator- It multiplies two operands.

/ operator- It divides numerator by de-numerator.

% operator- It is a modulus operator.

++ operator- It is increment operator, it increases integer value by one.

-- operator- It is decrement operator, it decreases integer value by one.

Logical Operators

In C++ there are following Logical operators supported.

|| operator- It is Logical OR operator, condition becomes true when any of the two operands are non-zero.

&& operator- It is Logical AND operator, condition becomes true when both the operands are non-zero.

! operator- It is Logical NOT operator that use to reverse the logical form of its operands. This operator will be false when a condition is true.

Relational Operators

In C++ there are following Relational operators supported.

== operator- This operator check the value of two operands are equal or not, if yes then condition will be true.

> operator- This operator check the value of left operand is greater than the value of right one, if yes then condition will be true.

< operator- This operator check the value of left operand is less than the value of right one, if yes then condition will be true.

>= operator- This operator check the value of left operand is greater than or equal to the value of right one, if yes then condition will be true.

<= operator- This operator check the value of left operand is less than or equal to the value of right one, if yes then condition will be true.

!= operator- This operator check the value of two operands are equal or not, if values are not equal then condition will be true.

Assignment Operators

In C++ there are following Assignment operators supported.
(=, +=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)

Bitwise Operators

These operators are using bit by bit operation and works on bits. In C++ there are following Bitwise operators supported.

(&, |, ^, ~, <<, >>,)

Variables

Variables are memory location in C++ that is used to store data on memory.

Variable name can consist of alphabets, numbers and start with underscore character and the first character of variables should always be alphabet not digit and blank space not allowed.

Data Types

A data types work as which types of data will store in variables and also work as memory storage of data. Data types either user defined data types or standard data types.

There are four main data types in C++.

char

int

float

double

char

This data type is used for character data types to represents letters and symbols.

Signe char- represent signed character.

unsigned char- represent unsigned character.

char- represent character.

wcahr_t- represent wide character.

char16_t- represent UTF-16 character.

char32_t- represent UTF-32 character.

int

This data type is values which have no decimal and it can be positive and negative such as- 10 or -10. Its values ranging from -32768 to 32767. It does not have fraction part.

int.

short int.

lont int

float

This data type contain a floating point number and a number that contain a fraction part. Its values ranging is between +/-3.4e38 to +/-3.4e38. It usually floating point numbers has decimal places.

double

This data type is large real number and its values ranging is from 1.7x10-308 to 1.7x10+308.

Modifiers

If we want to change the nature and working rules of any data types, then some specific words are used these are called modifiers.

There are two types of modifiers used in C++.

Size modifiers

Sign modifiers

Size Modifiers

If user wants to increase or decrease the actual size of data types then we must have to use size modifiers. There are two types of Size modifiers supported in C++ program.

Long– to increase the size.

Short – to decrease the size.

Sign Modifiers

If we want to fix the sign of the data types then we can use signed and unsigned modifiers. By the use of sign we can fix the data types to store only “+Positive” value and with use of unsigned we can fix “-Positive” values only.

Control structures

Control structures are statements that modify the sequence of program in certain conditions, during the execution it may repeat the code or take decisions.

In C++ control structures instruct to specify that what done by our program.

There are three categories of Control structures.

Selection Statements

Iteration Statements

Jump Statements

Selection Statements

There are some selection statements supported in C++ program.

if Statement

if else statement

Switch statement

Iteration Statements

There are some Iteration statements supported in C++ program.

for loop

while loop

do while loop

Jump Statements

There are some Jump statements supported in C++ program.

goto

break

continue

if Statement

Syntax

if(expression)
{ Statements }

Program

#include <iostream.h>
using namespace std;
void main()
{
int a=400;
int b=800;
if (b>a)
{
cout << "B is greater than A";
}
}

Result

B is greater than A

if else Statement

Syntax

if(expression)
{ Statements }
else
{ Statements }

Program

#include <iostream.h>
using namespace std;
void main()
{
int a=100;
int b=200;
if (a>b)
{
cout << "A is greater than B";
}
else
{
cout << "B is greater than A";
}

Result

B is greater than A

switch Statement

Syntax

switch(expression)
{
case1:
Statements
break
case2:
Statements
break
.
.
default
Statements
}

Program

#include <iostream.h>
using namespace std;
int main(void)
{
int day;
cout << "Enter the day number of week between 1-7:";
cin >> day;
switch(day)
{
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
default:
cout << "Sunday";
break;
}
}

Result

Enter the day number of week between 1-7: 2
Tuesday

for loop Statement

Syntax

for(initialization; condition; increment)

Program

#include <iostream.h>
using namespace std;
int main(void)
{
int i;
for(i= 1;i<5;i++)
{
cout << "run for loop at: " << i << " :times" << endl;
}
}

Result

run for loop at: 1 :times
run for loop at: 2 :times
run for loop at: 3 :times
run for loop at: 5 :times

while loop Statement

Syntax

while(condition) statement;

Program

#include <iostream.h>
void main()
{
int n;
cout << "Enter a number > 0:";
cin >> n;
while(n>0)
{
cout <<"Decremented value is:"<< n <<\n';
n--;
};
cout << "Enter a valid number" <<'\n';
}

Result

Enter a number > 0:4
Decremented value is:4
Decremented value is:3
Decremented value is:2
Decremented value is:1

do while Statement

Syntax

do
{statement;}
while(condition);

Program

#include <iostream.h>
using namespace std;
int main()
{
int n;
cout << "Number of times to display Hello KF:";
cin >> n;
do
{
cout << "oops! \n" << endl;
n--;
}while(n>0);
}

Result

Number of times to display KF:0
oops!

break Statement

Syntax

break;

Program

#include <iostream.h>
int main()
{
int i;
for ( i=0 ; i<10 ; i++ )
{
cout << "Counter value is:" << i << '\n';
if (i==5) { break; }
}
cout << "Exited loop by break statement." << '\n';
}

Result

Counter value is:0 Counter value is:1 Counter value is:2 Counter value is:3 Counter value is:4 Counter value is:5 Exited Loop by break statement.

goto Statement

Syntax

goto label;
.
.
label:

Program

#include <iostream.h>
void main()
{
int i;
cout << "Enter a Alphabet A,B,C:";
cin >> i;
switch(i) {
case 1:
cout << "A" << '\n';
goto exited;
case 2:
cout << "B" << '\n';
goto exited;
case 3:
cout << "C" << '\n';
goto exited;
default:
cout << "Enter a valid Alphabet" << '\n';
break;
}
exited:
cout << "Exited loop" << endl;
}

Result

Enter a Alphabet A,B,C:A
One
Exited Loop

continue Statement

Syntax

continue;

Program

#include <iostream.h>
using namespace std;
int main ()
{
int a = 9;
do
{
if( a == 13)
{
a = a + 1;
continue;
}
cout << "value of a:: " << a << endl;
a = a + 1;
}while( a < 15 );
return 0;
}

Result

value of a:: 9
value of a:: 10
value of a:: 11
value of a:: 12
value of a:: 14

Functions

Functions are separate individual modules designed in C++ programs.

A function is an area where we can declare the calculation part and can call it up to multiple times but appears in the code once.

By making functions we can decompose our program in separate blocks which are inter-linked with “main”.

Syntax

main()
{
…function body
return 0;
}

There are two types of functions in C++.

Library function.

User defines function.

Pre-defined or Library function

Those functions which are predefine in their header files i.e. (math.h, time.h, ctype.h) and can directly use without giving the definition of the function.

These functions are invoked through their specific header file.

Function using

ceil(), floor()

Example

#include <iostream.h>
#include <math.h>
void main()
{
double n;
cout << "Please enter a real number: ";
cin >> n;
// Compute the smallest and the largest of the real number
cout << "The ceil(" << n << ") = " << ceil(n) << endl;
cout << "The floor(" << n << ") = " << floor(n) << endl;
}

User defines function

These functions have to be specifically designed by the user to solve any problem these functions must have the definition of the calculation.

We do not need to attach any header file to invoke these functions.

Syntax

return_type function_name (Parameter1, Parameter2,…)
{
function body
}

It is a function prototype example.

Example

#include <iostream>
using namespace std;
int mult ( int a, int b );
int main()
{ int a;
int b;
cout<"Please input two numbers: ";
cin>> a >> b;
cin.ignore();
cout<<"The product of two numbers is: "<< mult ( a, b ) <<"\n";
cin.get();
}
int mult ( int a, int b )
{
return a * b;
}

Classes

A class is a technique to hold the data structures and functions. It is a way to allow user to creating and separate specific user defined data types.

It is the most powerful feature of C++.

When we defined the class starts with a keyword class followed by a class name and the body of the class enclosed with two curly braces and use semicolon at the end of class to terminate it same as structure.

The keywords private and public are called visibility labels.

Word private makes the data and function private and accessible inside only the class whereas, keyword public makes the data and function public and can be accessed both outside and inside the class.

Declaration of class

Class class_name
{
private:
some data;
function declarations;
public:
some data;
function declarations;
};

Example

class image
{
private:
int width;
int height;
char *pixels;
public:
int get_width();
int get_height();
char get_pixel(int x, int y);
void set_pixel(int x, int y, char value);
void save(char * filename);
};

Objects

In class instantiation of data types knows as objects in C++.

Relationship of object with class same as variable has with data types, class variables are also known as objects in C++.

An object contains the property of a class.

Example

Product x;

Here, x is the object of type product. One or more than one objects can be declared in one statement.

Example

Product x, y, z;

Syntax

Class_name Object_name {
…
Public
…
}

Example

class Y {
// members of class Y
};
int main()
{
Y obj; // declare a class object of class type Y
}

Member functions in Classes

In C++ member functions are those functions which are declare inside and outside the definition of the class.
It can be defined into two places.

Inside the class definition.

Outside the class definition.

Inside the class definition

In this definition we can directly define the function inside the class definition.

Example

class Product {
int productID;
float price;
public:
void getdata(int a, float b);
//function
void putdata(void) // defined inside class definition
{
Cout<< productID << “\n”;
Cout<< price << “\n”;
}
};

Outside the class definition

In this definition we have to define the function inside the class definition and then defined it outside the class definition.

Syntax

Creturn_type class_name :: function_name(declaration)
{
Function body…
}

Example

class cube {
public:
int side;
int getVolume();
}
//function
int cube :: getVolume() // defined outside class definition
{
return side*side*side;
}

Inheritance

Inheritance is one of the most important features of Object Oriented Programming.

It is a technique to reuse the existing classes without any modification and produce hierarchical relationship between them.

It acquires the properties and characteristics of one class to another class.

A class which inherited the properties to another class known as Parent, Base class whereas class which inherits the properties of another class known as Derived, sub or child class.

There are five types of Inheritance in C++.

Single Inheritance.

Multiple Inheritances.

Multilevel Inheritance.

Hierarchical Inheritance.

Hybrid Inheritance.

Syntax

class_name subclass_name : accessed_mode base_class_name
{
…
Members of Sub class
…
};

Example

#include <iostream>
using namespace std;
//Parent class
class Cars
{
public:
int Wheels = 4;
};
//Derived class
class Bike : public Cars
{
public:
int tyres = 2;
};
int main()
{
Bike b;
Cout<< b.Wheels;
Cout<< b.tyres;
return 0;
}

Single Inheritance

In this inheritance one derived class inherits from only one parent class.

Multiple Inheritances

In this inheritance one derived class inherits from two or more than two parent class.

Multilevel Inheritance

In this inheritance a class derived from another derived class inherits from one parent class.

Hierarchical Inheritance

In this inheritance multiple derived classes inherit from one parent class.

Hybrid Inheritance

It is the combination of both multilevel and multiple inheritance.

Polymorphism

Polymorphism is one of strategic features of object oriented programming that’s mean having many forms. Polymorphism rolls up when a hierarchy of classes and they are related by inheritance.

There are two types of polymorphism in C++ programming.

Compile time polymorphism.

Run time polymorphism.

Compile time polymorphism

In this polymorphism object is enclosing to the function call at the compile time itself known as static binding or static linkage or early binding.

Run time polymorphism

In this polymorphism object is enclosing to the function call at the run time.

Example of polymorphism

#include <iostream>
using namespace std;
class Shapes {
protected:
int width, height;
public:
Shapes(int x=0, int y=0)
{
width = x;
height = y;
}
int area()
{
cout << "Parent area:" <<endl;
return 0;
}
};
class Rectangle: public Shapes
{
public:
Rectangle( int a=0, int b=0)
{
Shapes(a, b);
}
int area()
{
cout << "Rectangle area:" <<endl;
return (width * height);
}
};
class Triangle: public Shapes
{
public:
Triangle( int a=0, int b=0)
{
Shapes(a, b);
}
int area()
{
cout << "Rectangle area:" <<endl;
return (width * height / 2);
}
};
// Main function for the program
int main( )
{
Shapes *shapes;
Rectangle rect(20,7);
Triangle tria(20,5);
// store the address of Rectangle
shapes =▭
// call rectangle area.
shapes->area();
// store the address of Triangle
shapes = &tria;
// call triangle area.
shapes->area();
return 0;
}

After compiling and executed the above code the following result will be received.

Parent class area

Knowledge flow: more eBooks and Apps

Get more eBooks

Get more apps from Google Play store

Get more apps from Amazon app store