0% found this document useful (0 votes)
310 views124 pages

C New

The document provides an overview of the history and development of the C++ programming language. It discusses that C++ development started in 1979 by Bjarne Stroustrup at Bell Labs as an enhancement to the C language to support object-oriented programming. It was initially called C with Classes but later became known as C++. The document outlines the different versions of C++ that were developed over time including Visual C++, Borland C++, Turbo C++, and ANSI C++. It also provides some basic information on C++ concepts and features.

Uploaded by

Riaz Mir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
310 views124 pages

C New

The document provides an overview of the history and development of the C++ programming language. It discusses that C++ development started in 1979 by Bjarne Stroustrup at Bell Labs as an enhancement to the C language to support object-oriented programming. It was initially called C with Classes but later became known as C++. The document outlines the different versions of C++ that were developed over time including Visual C++, Borland C++, Turbo C++, and ANSI C++. It also provides some basic information on C++ concepts and features.

Uploaded by

Riaz Mir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 124

C++ History

Background History :

1. C++ Development started in 1979.

2. During the creation of Ph.D. thesis, Bjarne Stroustrup worked with language called Simula.

3. Simula is basically useful for the simulation work.

4. Simula was first language to support object-oriented programming paradigm

5. Bjarne Stroustrup identified that this OOP features can be included in the software

development.

6. After that Bjarne Stroustrup started working on the C language and added more extra OOP

features to the classic C.

7. He added features in such a fashion that the basic flavour of C remains unaffected.

8. C++ includes some add-on features such as classes, basic inheritance, in-lining, default

function arguments, and strong type checking

Basic History of C++

1. During 1970 Dennis Ritchie created C Programming language.

2. In the early 1980s, also at Bell Laboratories, another programming language was created

which was based upon the C language.

3. C++ is also called as C with classes

4. Stroustrup states that the purpose of C++ is to make writing good programs easier and more

pleasant for the individual programmer.

5. C++ programming language is extension to C Language.


6. In C we have already used increment operator (++). Therefore we called C++ as

Incremented C means Extension to C.

Creator of C++

Versions of C++ Language


There are several versions of C++ Programming Language

1. Visual C++

2. Borland C++

3. Turbo C++ (To Read more click here)

4. Standardize C++ [ANSI C++]

Reference Links :

1. http://www.hitmill.com/programming/cpp/cppHistory.html

2. http://en.wikipedia.org/wiki/C%2B%2B

C++ Portability

How do Java and C# create cross-platform portable programs, and why cant C++
?
Why C++ is not cross platform dependent ? Why C++ is not a portable ? How Java is portable ?
What makes Java and C# portable ? We have summarized all the reasons that makes Java and C#
portable and C++ :
Reason :
Consider Scenario of C++ Language

1. Portability of any language depends on the object code created by compiler.

2. C++ Compiler produces machine code which is directly executed by the CPU.

3. C++ Code is thus machine dependent and tied to particular Operating System (OS).

4. If we try to execute C++ program on the another Operating C++ then we must recompile

program before executing program.

Consider Scenario of Java Programming Language

1. Java is created by Sun Micro System. [See : What is Java ?]

2. Java Compiler produces Intermediate code called Byte Code.

3. Byte Code i.e intermediate code is executed by the Run Time Environment.

4. In Java Run Time Environment is called as JVM [ Java Virtual Machine]


5. If we have JVM already installed on any platform then JVM can produce machine dependent

Code based on the intermediate code.

6. Here is descriptive reason Why Java is portable ?

Consider Scenario of C# Programming Language

1. C# was created by Microsoft.

2. C# compiler produces intermediate code called as MSIL. (MicroSoftIntermediate Language).

3. MSIL i.e intermediate code is executed by CLR (Common Language Run Time)

4. If we have CLR already implemented on any platform then CLR can produce machine

dependent Code based on the intermediate code.

5. Re-commanded Article : Difference between C# and Java

..

C++ First Program


In the previous chapters we have learnt the basic history and some of the reasons why C++ is not
portable like C# and Java.

Sample C++ Program

/*
This is a simple C++ program.
Call this file Sample.cpp.
*/

#include <iostream>
using namespace std;

// A C++ program begins at main().


int main()
{
cout << "C++ is power programming.";
return 0;
}

Output :

C++ is power programming.

Explanation : First C++ Program

Consider the following line in the programs

/*
This is a simple C++ program.
Call this file Sample.cpp.
*/
1. It is Comment in C++ Language which is ignored by compiler

2. Comments are written for user understanding.

#include <iostream>

3. C++ uses different header files like C.

4. Include statement tells compiler to include Standard Input Output Stream inside C++

program.

5. This header is provided to user along with the compiler.

int main()

6. Each C++ program starts with the main function like C Programming.

7. Return type of the C++ main function is integer, whenever main function returns 0 value to

operating system then program termination can be considered as smooth or proper.

enever some error or exception occurs in the program then main function will return the non zero

value to operating system.

cout << "C++ is power programming.";

9. C++ Insertion operator (<<) is used to display value to the user on the console screen.
return 0;

10. return statement sends status report to the operating system about program execution whether

program execution is proper or illegal.

C++ Concept Overview

Overview of C++ Programming Language

1. C++ was developed by Bjarne Stroustrup in the 1980 at Bell Labs.

2. The name C++ comes from the C increment operator ++, which adds 1 to the value of a

variable.

3. The C++ is an extensive version of language C.


4. Every C program can be consider as C++ Program but reverse is not true.

5. C++ supports for the Structured programming and also it fully supportsOOP

1. Encapsulation

2. Data hiding

3. Inheritance

4. Polymorphism.

6. C++ is also called as C with classes.

7. C++ is first popular object oriented programming language.

8. C++ is further modified and standardize to ANSI version nearly in 2000

9. C++ is modified by Microsoft in order to support visual applications called Visual C++.

10. C++ is a

o Statically typed

o Free-form

o Multi-paradigm

o Compiled

o General-purpose programming language.

o Intermediate-level language,

11. Most of the C++ concepts are considered as basic concepts for Java Programming.

C++ Design Aims : Why C++ was designed ?

1. C++ makes programming more enjoyable for serious programmers.

2. C++ is a general-purpose programming language that

o is a better C

o supports data abstraction

o supports object-oriented programming

.
C++ Compilers & IDE

C++ Compilers : 5 most popular C++ IDE / Compiler used to Run C++ Program

C++ Compilers are OS dependent so writing complex C++ Program is not an easy task , we have to
put lot of efforts to write C++ Program if we dont have IDE. IDE makes our task easy. We have list
of different compilers used to compile and execute C++ programs on the different Operating
Systems (OS). We have summarized all the compiles in the below list

1. Borland C++ / Turbo C++ [Old and most popular IDE]

2. Visual C++ [Microsoft Platform]

3. Dev C++

4. GCC

5. Eclipse

C++ Compilers : (You may get List of C++ Compilers Here)


Borland C++ :

Borland C++ is a C and C++ program

,,,,,,,,,,,,,,,

C++ Program Structure

Structure of C++ Program : Layout of C++ Program

C++ Programming language is most popular language after C Programming language. C++ is first
Object oriented programming language.We have summarize structure of C++ Program in the
following Picture
Structure of C++ Program

Section 1 : Header File Declaration Section

1. Header files used in the program are listed here.

2. Header File provides Prototype declaration for different library functions.

3. We can also include user define header file.

4. Basically all preprocessor directives are written in this section.

Section 2 : Global Declaration Section

1. Global Variables are declared here.

2. Global Declaration may include

o Declaring Structure

o Declaring Class

o Declaring Variable
Section 3 : Class Declaration Section

1. Actually this section can be considered as sub section for the global declaration section.

2. Class declaration and all methods of that class are defined here.

Section 4 : Main Function

1. Each and every C++ program always starts with main function.

2. This is entry point for all the function. Each and every method is called indirectly through

main.

3. We can create class objects in the main.

4. Operating system call this function automatically.

Section 5 : Method Definition Section

1. This is optional section . Generally this method was used in C Programming.

C++ Comments

What is Comments in C++ ?


[one_third last=no] [/one_third]
Comment in C++ Programming is similar as that of in C .Each and every language will provide this
great feature which is used to document source code.We can create more readable and eye catching
program structure using comments.We should use as many as comments in C++ program. Comment
is non executable Statement in the C++.

Types of Comment in C++ Programming

We can have two types of comment in Programming

1. Single Line Comment

2. Multiple Line Comment

Single Line Comments in C++

cout<<"Hello"; //Print Hello Word

cout<<"www.c4learn.com"; //Website

cout<<"Pritesh Taral"; //Author

Single Line comment starts with // symbol.


Remaining line after // symbol is ignored by browser.
End of Line is considered as End of the comment.

Multiple Line Comments in C++

int main()
{
/* this comment
can be considered
as
multiple line comment */

cout << "Hello C++ Programming";

return(0);
}

Multi Line comment starts with /* symbol.


Multi Line comment ends with */ symbol.

How to use Comment more efficiently in C++ Programming

1. Comment for User Documentation.

2. Hiding Non-usable Code.

3. Hiding Single Statement.

4. Comment used to explain particular language statement

1. Comment used for Documentation

/* Name : Main Function


* Parameter : None
* Return Value : Integer
*/

int main()
{

cout << "Hello C++ Programming";

return(0);
}

Above comment is used for documentation. We use This type of Documentation to summarize C++
code.

2. Comment used to Hide Non-usable line.

<script type="text/javascript">
// document.write("<h1>Heading</h1>");

document.write("<p>Google</p>");
document.write("<p>Yahoo</p>");
</script>

We have used comment to prevent execution of single line.

// document.write("<h1>Heading</h1>");

3. Comment used to Hide Non-usable Multiline Code.

int main()
{
person p1,p2;

p1.getData();
p2.putData();
// p3.getData();

return(0);
}

4. Comment written after Statement

int main()
{
person p1,p2;
p1.getData(); // Get Personal Info
p2.putData(); // Save Personal Info

return(0);
}

Something About Comments :

1. Comments are non Executable Statements.

2. Comments are always neglected by compiler.

3. Comments are replaced by white spaces during the preprocessor phase.

4. Comments can be written anywhere and any number of times.

5. Comments can be used for documentation.

6. Comments can be Single Line or multiple line.

Bad Habits of Using Comments in C++ :

1. Dont Write Comment for statements that can be easily understood .

int main()
{
int age=0;
//initialize age to 0

return(0);
}

Read More : Wiki Article on Comment |

.
C++ cin

Cin : Extracting Input from User Using Keyboard

In C++ Extraction operator is used to accept value from the user.User can able to accept value from
user and that value gets stored inside value container i.e. Variable.

Syntax : Get Value from User

cin >> variable;

Explanation : Extraction Operator

Include <iostream.h> header file to use cin.

#include<iostream.h>//traditional C++

OR

#include<iostream>// ANSI Standard


using namespace std;

cin is used for accepting data from the keyboard.


The operator >> called as extraction operator or get from operator.
The extraction operator can be overloaded.
Extraction operator is similar to the scanf() operation in C.
cin is the object of istream class.
Data flow direction is from input device to variable.
Due to the use of input statement, the program will wait till the usertype some input and
that input is stored in variable.
Multiple inputs can be accepted using cin.

Live Example : Accepting Input From User


#include<iostream.h>
using namespace std;

int main()
{
int number1;
int number2;

cout<<"Enter First Number: ";


cin>>number1; //accept first number

cout<<"Enter Second Number: ";


cin>>number2; //accept first number

cout<<"Addition : ";
cout<<number1+number2; //Display Addition

return 0;
}
Output :

Enter First Number: 8


Enter Second Number: 8
Addition : 16

Different ways of using cin in c++


Way 1. Simple Use of cin and Extraction Operator:

int tempNumber;
cin >> tempNumber;

In above example, tempNumber is declared as integer variable.


when control comes over cin , Program waits for the input from user.
We have written integer variable after extraction operator so it will wait and expect integer
as input from user .
If you request an integer you will get an integer, character for character, string for string
etc

Way 2 : Cascading Multiple Variables in Cin

int a,b;
cin >> a >> b;

is similar to

int a,b;
cin >> a;
cin >> b;

While Accepting Two values cin consider next value when it found

1. Space

2. Tab

3. Newline.
*Note : In this case, User is forced to input two variables (a and b).

Way 3 : cin to get string

cin >> string ; //for getting string input

The extraction operator is also used for getting string.


When blank space is detected, extraction operator stops reading input.
cin allow us to enter only one word.
For reading entire line, we use getline() function.

C++ cout

Cout : Display Output to User Using Screen(Monitor)

In C++ Insertion operator is used to display value to the user. The value may be some message in the
form of string or variable.

Syntax : Display Value to User

cout << variable;

Explanation : Insertion Operator

Include <iostream.h> header file to use cin.

#include<iostream.h>//traditional C++

OR

#include<iostream>// ANSI Standard


using namespace std;

cout is used for displaying data on the screen.


The operator << called as insertion operator or put to operator.
The Insertion operator can be overloaded.
Insertion operator is similar to the printf() operation in C.
cout is the object of ostream class.
Data flow direction is from variable to output device.
We can still use printf() for displaying an output..
Multiple outputs can be displayed using cout.

Live Example : Displaying Output on Screen

#include<iostream.h>
using namespace std;

int main()
{
int number1;
int number2;

cout<<"Enter First Number: ";


/* Display the message to tell the
user to do appropriate action */
cin>>number1;

cout<<"Enter Second Number: ";


/* Display the message to tell the
user to do appropriate action */

cin>>number1;
cin>>number2;

cout<<"Addition : ";
cout<<number1+number2; //Display Result

return 0;
}

Output :

Enter First Number: 8


Enter Second Number: 8
Addition : 16

Different ways of using cout in c++


Way 1. Simple Use of cout and Insertion Operator:

int tempNumber=6;
cout << tempNumber;
In above example, tempNumber is declared as integer variable. And value 6 is assigned to it.
when control comes over cout , Program will display the output to screen.
Likewise we can display integer, character or string.

Way 2 : Cascading Multiple Variables in Cout

int a=10;
int b=20;
cout << a << b;

is similar to

int a=10;
int b=20;
cout << a;
cout << b;

Way 3 : cout to display string

cout << string ; //for displaying string output

or

cout << "Display String" ;

The extraction operator is also used for getting string.


When blank space is detected, extraction operator stops reading input.
cin allow us to enter only one word.
For reading entire line, we use getline() function.

Way 4 : Use of expression in cout

int num1;
int num2;

cin >> num1;


cin >> num2;

cout<< "Addition is : " << num1+num2 ;

Expression can be evaluated inside cout statement.


In above example, we are accepting 2 values from user.
The addition of two numbers is displayed on the screen
For that we use the expression for adding two numbers in the output statement directly.

Way 5 : Display Output on new line

We can use n or endl to print the output on new line.

cout << "Hello,n";


cout << "My name is nPooja...";

or

cout << "Hello," <<endl;


cout << "My name is" <<endl;
cout << "Pooja..." <<endl;

Output :

Hello,
My name is
Pooja...

*External Link : More on cout | cout Statement | Sample Example

C++ setw() : Setting Field Width


setw() : Setting field width Using Cout in C++ Programming

1. setw() is library function in C++.

2. setw() is declared inside #include<iomanip>

3. setw() will set field width.

4. setw() sets the number of characters to be used as the field width for the next insertion operation.

Syntax :

setw(num)

num is width to be set in order to insert next value.

Live Example 1 : Setting Width in C++

#include <iostream>
#include <iomanip>

using namespace std;


int main ()
{
cout << setw (10);
cout << "Pritesh" << endl;

return 0;
}

1. Now Length of String Pritesh is 7

2. We have set field width 10 so it will utilizes 7 fields

3. Remaining 3 fields are kept blank.

4. Default Justification : Left

Live Example 2 : Setting Width in C++

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
const int maxCount = 4;
const int width = 6;
int row;
int column;

for(row=1;row<=10;row++)
{
for(column = 1; column <= maxCount; column++)
{
cout << setw(width) << row * column;
}
cout << endl;
}

return 0;
}

Output :

1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
5 10 15 20
6 12 18 24
7 14 21 28
8 16 24 32
9 18 27 36
10 20 30 40

*External Link : setw

Get in Touch!

C++ Characteristics
C++ Provides huge Function Library thats why its popularity is increasing day by day and more
programmers are inclining towards C++ due to its multiple features

1. C++ is an Object Oriented Programming Language (OOPL).

2. C++ have huge Function Library

3. C++ is highly Flexible language with Versatility.

4. C++ can be used for developing System Software viz., operating systems, compilers, editors

and data bases.

5. C++ is suitable for Development of Reusable Software. , thus reduces cost of software

development.

6. C++ is a Machine Independent Language.

Advantages And Features Of Object Oriented


Programming

Advantages Of Object Oriented Programming :

Advantages Of Object Oriented Programming

OOP provides a clear modular structure for programs.


It is good for defining abstract data types.
Implementation details are hidden from other modules and other modules has a clearly
defined interface.
It is easy to maintain and modify existing code as new objects can be created with small
differences to existing ones.
objects, methods, instance, message passing, inheritance are some important properties
provided by these particular languages
encapsulation, polymorphism, abstraction are also counts in these fundamentals of
programming language.
It implements real life scenario.
In OOP, programmer not only defines data types but also deals with operations applied for
data structures.

Features Of Object Oriented Programming :

More reliable software development is possible.


Enhanced form of c programming language.
The most important Feature is that its procedural and object oriented nature.
Much suitable for large projects.
Fairly efficient languages.
It has the feature of memory management.

Learn C++ Programming Language : Step By Step Tutorials

Chapter 1 : History of C++

1.1 Brief History of C++

1.2 Why C++ Cannot Create Cross-Platform Codes like Java/C# ?


Chapter 2 : Overview of Object Oriented Concepts

2.1 Pillars of Object Oriented Programming Language

2.2 Procedural to Object Oriented Programming Migration

2.3 Why C++ is called as Object Oriented Programming Language ?

2.4 Creating namespace in C++

Chapter 2 : Overview of C++

3.1 First C++ Program

3.2 Overview of C++ Language

3.3 C++ IDE | Editor

3.4 Characteristics of C++ Programming

3.5 Structure of C++ Program

3.6 Comments in C++

3.7 Printing Message on Screen : Cout

3.8 Accepting Value from User : Cin

3.9 Setting field width


C++ Variable Naming

What is Identifier ?

Any used defined name given to the program element is called as identifier. (i.e Program elements
are identified by program with the identifier name)

Some Facts About Identifier :

1. It is name given to program element.

2. Identifier are the names is given by the programmer.

3. An identifier is used for any variable, function, data definition etc.

4. We can give any valid name to the identifier.

The rules in C++ for identifiers are :

1. Only Alphabets,Digits and Underscores are permitted.

2. Identifier name cannot start with a digit.

3. Key words cannot be used as a name.

4. Upper case and lower case letters are distinct.

5. Special Characters are not allowed

6. Global Identifier cannot be used as Identifier.

Sample Examples of C++ Identifier :


In the C++ programming language, an identifier is a combination of alphanumeric characters, the
first being a letter of the alphabet or an underline, and the remaining being any letter of the alphabet,
any numeric digit, or the underline.
Valid Examples are :

Identifier Note

Name Capital Letter and Small Letters are Allowed

name Small Letters are allowed

name_1 Digits and Underscore is allowed along with alphabets

Keywords are allowed but we have to change case of any letter


Int
or complete word

Keywords are allowed but we have to change case of any letter


INT
or complete word

_SUM Underscore at the first position is allowed in C++ language

sum_of_the_numbers We can concatenate multiple words with underscore

Best Style to concatenate multiple words (Changing case of


firstName
First Letter of Successive Word)

Identifier We can give concept name as Identifier name

As we are not going to include stdio.h header file we can use


printf
printf as identifier.

Invalid Examples are :

Identifier Explanation
int Keyword name cannot be given to Variable/Identifier

pow() is defined in math.h. This variable is legal if we havent included


pow math.h in our program. As soon as we include math.h header file in
program this identifier will be illegal.

$ sign can be used in other programming language for creating identifier,


$sum
however C/C++ do not support $ sign.

num^2 special characters are not allowed.

Spaces are not allowed in C++ programming language for declaring


num 1
identifier.

2num Digits are allowd but not as first Character

.C++ legal Characters

The set of characters used in C++ consists of

Token Example

Alphabets A-Z and a-z

Digits 0-9

Special characters $%^

The following table will depict the characters used in C++ Progeamming language

Special Characters Type Example


Special Characters Type Example

Arithmetic Operators +*/%

Logical Operators &!

Brackets (){}[]

Relational Operators <>=#

Other Symbols : ; _(underscore) >> ?

These all the characters are said to be valid characters in C++ programming language. We are using
these characters for the purpose of the declaring variable name,class name.

Some of the Definitions :

Term Definition

An alphabet is a standard set of letters (basic written symbols or


Alphabet
graphemes) for the listing of words

A digit is an element of a set that taken as a whole comprises a


Digits
system of Numeration

Special
ASCII printable characters are called as Special Characters
Character

..

C++ Identifiers : Tokens


We have already seen, which are the different types of characters that are considered legal in C++. In
this chapter we will be learning the token i.e basic building blocks of C++.

Tokens in C++ :

The group of characters that forms an Basic Building block is called as Token. Tokens are of
following 4 types of token in C++ :

A. Token Type 1 : Identifier

Various data items with symbolic names in C++ is called as Identifiers. Following data items are
called as Identifier in C++

1. Names of functions

2. Names of arrays

3. Names of variables

4. Names of classes

The rules of naming identifiers in C++ :


1. C++ is case-sensitive so that Uppercase Letters and Lower Case letters are different

2. The name of identifier cannot begin with a digit. However, Underscore can be used as first

character while declaring the identifier.

3. Only alphabetic characters, digits and underscore (_) are permitted in C++ language for

declaring identifier.

4. Other special characters are not allowed for naming a variable / identifier

5. Keywords cannot be used as Identifier.

Some Examples of Identifier in C++ :

Identifier Validity Reason

1digit Invalid Digit at first location is not allowed

digit-1 Invalid Special characters other than underscore is not allowed

num 1 Invalid Space not allowed

C++ Keywords

In C++, keywords are reserved identifiers which cannot be used as names for the variables in a
program.

C++ Keyword List :

asm else operator template

auto enum private this

break extern protected throw

case float public try


asm else operator template

catch for register typedef

char friend return union

class goto short unsigned

const if signed virtual

continue inline sizeof void

default int static volatile

delete long struct while

double new switch -

Keywords cannot be used for the

1. Declaring Variable Name

2. Declaring Class Name

3. Declaring Function Name

4. Declaring Object Name

C++ Constants

Constants are the items whose value cannot be changed during the program execution.
C++ Constants :

Explanation and Meaning :

Type of
Explanation
Constant

Numeric These are Integer Numbers or floating numbers such as 11.30 or


Constant 13.

Character
These are alphabets i.e A-Z or a-z
Constant

String String Constants are the Combinations of Alphabets Numbers and


Constant Special Characters under single constant name
C++ Operators

An operator is a symbol which tells compiler to take an action on operands and yield a value. The
Value on which operator operates is called as operands. C++ supports wide verity of operators.
Supported operators are listed below

Operator Explanation

Arithmetic Operators Used for arithmetic operations

Relational Operators Used for specifying relation between two operands

Logical Operators Used for identifying the truth value of the expression

Bitwise Operators Used for shifting the bits

Assignment Operators Used for assigning the value to the variable

Misc Operators -

Arithmetic Operators :

Consider that we have A = 20 and B = 10

Operator Description Example

+ Adds two operands or variables A + B = 30

- Subtracts second operand from the first A B = 10

* Multiplies both operands A * B = 200

/ Divides numerator by denominator A/B=2

After dividing the numberator by denominator


% A%B=0
remainder will be returned after division

++ Increment operator will increases integer value by one A++ = 21

#8211; - Decrement operator will decreases integer value by A- #8211; = 19


Operator Description Example

one

Relational Operators:

Consider that A = 40 and B = 20

Symbol Meaning Example

A > B returns
> Greater than
true

A < B returns
< Less than
false

A >= B returns
>= Greater than equal to
false

A <= B returns
<= Less than equal to
false

A == B returns
== Equal to
false

A != B returns
!= Not equal to
true

#91;/table#93;

Logical
Operators :

Consider that A = 0 and B = 0

Operator Description Example

Logical AND If both the operands are non-zero then only (A && B) is
(&&) condition becomes true false.

If both the operands are zero then only


Logical OR (||) (A || B) is true.
condition becomes false
Symbol Meaning Example

It will reverses the state of its operand i.e


Logical NOT (!) (!A) is true.
true will become false

C++ While loop

C++ While loop :

1. The while loop is used for repetitive execution of the statements based on the given

conditions.

2. If condition fails then control goes outside the while loop. If condition becomes true then

while loop body will be executed.

3. True condition can be any non-zero number and Zero is considered as false condition

Syntax for the while-loop :

while(condition)
{
statement(s);
}

Flowchart of the while loop :


Example of the while loop :

#include <iostream>
using namespace std;

int main ()
{
// Local variable declaration
int num = 5;

// while loop execution


while( num < 10 )
{
cout << "Number : " << num << endl;
num++;
}
return 0;
}

Output :

Number : 5
Number : 6
Number : 7
Number : 8
Number : 9

Explanation :
In the above program we have declared a variable having initial value equal to 5.

int num = 5;

Now in the while condition, we have variable value less than 9 so the condition becomes true so
while body gets executed.

while( num < 10 )

Now in the while loop if the value of num becomes 10 then the condition becomes false, in that case
while loop body will not be executed.

Some more example of while loop :


A. Infinite while loop
In the below example, we have infinite while loop -

while( 1 )
{
cout << "Number : " << num << endl;
num++;
}

Now we know that any character variable can converted to integer using the ASCII representation. so
we can also have infinite loop like this -

while( 'A' )
{
cout << "Number : " << num << endl;
num++;
}

C++ for loop

In the previous chapter we have already seen the while loop in C++programming language.

C++ for loop :


The for-loop is also used to execute some statements repetitively for a fixed number of times.
Syntax of the for loop is as follow

for ( init; condition; increment )


{
statement(s);
}

Example of for loop :

#include <iostream>
using namespace std;

int main ()
{
// for loop execution
for(int i = 0; i < 10; i = i + 1 )
{
cout << "value of i : " << i << endl;
}
return 0;
}
Output :

value of i : 0
value of i : 1
value of i : 2
value of i : 3
value of i : 4
value of i : 5
value of i : 6
value of i : 7
value of i : 8
value of i : 9

Explanation of the program :


For loop comrpise of the three steps.

1. In first step, the initial expression is evaluated. Initial value is provided to the loop index

variable.

2. In next step, the test-expression is evaluated. If the value is non-zero, the loop is executed and if

the value is zero, the loop is terminated without execution.

3. In the third step of the execution of for-loop, the update expression is evaluated.

C++ For loop flowchart :


Different ways of the for loop are also explained in our C section

C++ infinite for loop :

#include <iostream>
using namespace std;

int main ()
{
for(;;)
{
cout << "Hello World !";
}
return 0;
}
C++ dowhile loop

In the our previous two chapters we have seen for loop and while loop.

C++ dowhile loop :

1. Unlike for and while loops, do..while loop does not test the condition before going in the loop.

2. do..while statement allow execution of the loop body once and after the execution of loop body

one time, condition will be checked before allowing the execution of loop body for second time.

3. do..while loop is exit controlled loop, i.e condition will be checked after the execution of the

body i.e at the time of exit.

4. dowhile loop is guaranteed to execute at least one time

Syntax of do..while loop :

do
{
statement(s);
}while( condition );

Example of do..while loop :

#include <iostream>
using namespace std;

int main ()
{
// Local variable declaration:
int i = 0;
// do loop execution
do
{
cout << "value of i : " << i << endl;
i++;
}while( i < 10 );

return 0;
}

Output :

value of i : 0
value of i : 1
value of i : 2
value of i : 3
value of i : 4
value of i : 5
value of i : 6
value of i : 7
value of i : 8
value of i : 9

Flowchart of do..while loop :


Difference between do..while and while loop :

do-while While

It is exit controlled loop It is entry controlled loop

The loop executes the statement at loop executes the statement only after testing
least once condition

The condition is tested before The loop terminates if the condition becomes
execution. false.

Infinite while loop :


Sometimes we need some special kind of loop which should execute the loop body for infinite
times. Loop whose body keeps executing infinite number of times is called as infinite loop.

while(1)
cout << "Hello";
In the above example, the condition part is replaced with the integer 1. i.e condition will be
always non-zero number so loop continues its execution for infinite time until stack overflow
occurres.

C++ Nested loops

When we write any loop statement within the another loop statement then that structure is called
as nested loop. We have already seen all the loops statements (while loop, do..while loop, for
loop)

Nesting of the loops :


Consider the following syntax of the nested loops

for(initialize; condition; increment)


{
for (initialize; condition; increment)
{
statement(s);
}
statement(s);
}

OR

while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}

OR

do
{
statement(s);
do
{
statement(s);
}while( condition );

}while( condition );

However we can use any combination of the loops in order to achieve nested loop structure.

Example of nested loop :


In this example we need to print all the combinations of the digits from 0 to 5. i.e 11,23 or 05

#include <iostream>
using namespace std;

int main ()
{
int i, j;

for(i=0; i<=5; i++) {

for(j=0; j <= 5; j++) {


cout << i << j <<" \t";
}
cout <<"\n";
}

return 0;
}

Output :

00 01 02 03 04 05
10 11 12 13 14 15
20 21 22 23 24 25
30 31 32 33 34 35
40 41 42 43 44 45
50 51 52 53 54 55

Explanation of the program :


In the outer for loop when the value of i becomes 0 then control enters into the inner loop where j
will take value from 0 to 5 considering the same value of i = 0

Value of i Value of j in inner loop

i=0 Consider j = 0 1 2 3 4 5

i=1 Consider j = 0 1 2 3 4 5

i=2 Consider j = 0 1 2 3 4 5

i=3 Consider j = 0 1 2 3 4 5

i=4 Consider j = 0 1 2 3 4 5

i=5 Consider j = 0 1 2 3 4 5
C++ break statement

In C++ break statement is used for the termination of the loop statement and switch case
statement. Below is the syntax of the break statement.

break;

#1. C++ Break Statement Example :


Example of the break statement is used below

#include <iostream>
using namespace std;

int main ()
{
// Declaring Local variable
int count = 0;

// do loop execution
do
{
cout << "Count : " << count << endl;
count++;
if( count > 5)
{
// Terminate the loop
break;
}
}while( count < 20 );

return 0;
}

Output :

Count : 0
Count : 1
Count : 2
Count : 3
Count : 4
Count : 5

Explanation :
In the above example, while condition specified that, loop will iterate 20 times.

while( count < 20 )

Now in the loop body we have written the simple condition which tells us to break the loop if the
count value becomes greater than 5.

if( count > 5)


{
// Terminate the loop
break;
}

#2. C++ Break Statement in nested loop Example :


If we are using the nested loop and we used break statement in the inner loop then break will
terminate the inner loop.
do
{
for(int i=0; i<5; i++) {
cout << i;
if(i == 1)
break;
}

cout << "Count : " << count << endl;


count++;

}while( count < 20 );

In the above example, outer loop will be executed as usual, but the inner loop will be terminated
as soon as the value of i becomes 1.

Flow diagram :
C++ continue statement

In the break statement tutorial we have seen the way by using which we can terminate the loop
whenever require. Similarly we can use continue statement to skip the part of the loop.

C++ continue statement :

The continue statement forces the next iteration of the loop to take place, skipping remaining code in
between.

1. In the case of the for loop as soon as after the execution of continue statement,

increment/decrement statement of the loop gets executed. After the execution of increment

statement, condition will be checked.

2. In case of the while loop, continue statement will take control to the condition statement.

3. In case of the do..while loop, continue statement will take control to the condition statement

specified in the while loop.

Example #1. Continue statement :


#include <iostream>
using namespace std;

int main ()
{
int count = 0;
do
{
count++;
if(count > 5 && count < 7)
continue;

cout << "Count : " << count << endl;


}while( count < 10 );

return 0;
}

Output :

Count : 1
Count : 2
Count : 3
Count : 4
Count : 5
Count : 7
Count : 8
Count : 9
Count : 10

In the above example, when count = 6 then both conditions become true and thus continue statement
gets executed in that case.

C++ Continue Statement Flowchart :


Courtesy : Tutorialspoint

C++ goto statements

A goto statement used as unconditional jump from the goto to a labeled statement in the same
function.

C++ goto statement :

1. goto statement is used for unconditional jump.

2. goto statement makes difficult to trace the control flow of program

3. goto statement should be avoided in order to make smoother program.

Syntax :

goto label;
..
.
label: statement;

Example #1 : Goto Statement :

#include <iostream>
using namespace std;

int main ()
{
int num = 1;
STEP:do
{
if( num == 5)
{
num = num + 1;
goto STEP;
}

cout << "value of num : " << num << endl;


num = num + 1;

}while( num < 10 );


return 0;
}

Output :

value of num : 1
value of num : 2
value of num : 3
value of num : 4
value of num : 6
value of num : 7
value of num : 8
value of num : 9

Different types of goto :

C++ if statement

In C++ if statement is used to check the truthness of the expression. Condition written inside If
statement conconsists of a boolean expression. If the condition written inside if is true then if block
gets executed.
Syntax :

If statement is having following syntax

if(boolean_expression)
{
// statement(s) will execute if the
// boolean expression is true
}

Example : C++ If Statement

#include <iostream>
using namespace std;

int main ()
{
// Declaring local variable
int num = 5;

// check the boolean condition


if( num > 4 )
{
cout << "num is greater than 4" << endl;
}
cout << "Given number is : " << num << endl;

return 0;
}

Output :

Compiled C++ code will produce following output

num is greater than 4


Given number is : 5
Explanation :

In the above program, In the if condition we are checking the following condition

if( num > 4 )

If the above condition evaluates to true then the code written inside the if block will be executed.
Otherwise code followed by if block will be executed.

Note #1 : Curly braces

Complete if block is written inside the pair of curly braces. If we have single statement inside the if
block then we can skip the pair of curly braces

if( num > 4 )


cout << "num is greater than 4" << endl;

C++ ifelse statement

If block sometimes followed with the optional else block. When the if condition becomes false then
else block gets executed.

Syntax of C++ If-else :

if(boolean_expression)
{
// True Block
}
else
{
// False Block
}

If the boolean_expression becomes false then then else block will be executed. If the boolean
expression becomes true then by default true block will be executed.
If Else Flowchart :

Example : C++ If Else Statement

#include <iostream>
using namespace std;

int main ()
{
// declare local variable
int marks = 30;

// check the boolean condition


if( marks > 40 )
{
// if condition is true
cout << "You are pass !!" << endl;
}
else
{
// if condition is false
cout << "You are fail !!" << endl;
}
return 0;
}

Output :

You are fail !!

C++ else..if ladder

In the previous chapters we have seen different tutorials on if statement and if-else statement.

When we need to list multiple else ifelse statement blocks. We can check the various conditions
using the following syntax

Syntax : C++ Else if ladder

if(boolean_expression 1)
{
// When expression 1 is true
}
else if( boolean_expression 2)
{
// When expression 2 is true
}
else if( boolean_expression 3)
{
// When expression 3 is true
}
else
{
// When none of expression is true
}

When the first Boolean condition becomes true then first block gets executed.

When first condition becomes false then second block is checked against the condition. If second
condition becomes true then second block gets executed.

Example : Else if ladder

#include <iostream>
using namespace std;

int main ()
{
// declare local variable
int marks = 55;

// check the boolean condition


if( marks >= 80 )
{
// if 1st condition is true
cout << "U are 1st class !!" << endl;
}
else if( marks >= 60 && marks < 80)
{
// if 2nd condition is false
cout << "U are 2nd class !!" << endl;
}
else if( marks >= 40 && marks < 60)
{
// if 3rd condition is false
cout << "U are 3rd class !!" << endl;
}
else
{
// none of condition is true
cout << "U are fail !!" << endl;
}

return 0;
}

Output :

U are 3rd class !!

Explanation :

1. Firstly condition 1 specified in the if statement is checked. In this case the condition becomes

false so it will check the 2nd condition in the else if block.

2. Now 2nd block condition also evaluates to be false then again the 2nd block will be skipped

and 3rd block condition is checked.

3. In the above example the condition specified in the 3rd block evaluates to be true so the third

block gets executed.

Flowchart diagram :
Some rules of using else if ladder in C++ :

Keep some important things in mind

1. if block can have zero or one else block and it must come after else-if blocks.

2. if block can have zero to many else-if blocks and they must come before the else.
3. After the execution of any else-if block none of the remaining else-if block condition is

checked.

C++ Switch Case : Statement

C++ provides the multi-way decision statement which helps to decrease the complexity of the
program.

Switch case statement is best way to deal with the else-if nesting.

if(Condition 1)
Statement 1
else
{
Statement 2
if(condition 2)
{
if(condition 3)
statement 3
else
if(condition 4)
{
statement 4
}
}
else
{
statement 5
}
}

Consider the above scenario, we can overcome this situation by using the switch case statement
syntax like below

C++ Switch Case Syntax :

switch(expression)
{
case value1 :
body1
break;

case value2 :
body2
break;

case value3 :
body3
break;

default :
default-body
break;
}
next-statement;

Flow Diagram :
*Steps are Shown in Circles.

Example :

#include <iostream>
using namespace std;

int main ()
{
// local variable declaration:
char grade = 'C';

switch(grade)
{
case 'A' :
cout << "A grade" << endl;
break;
case 'B' :
cout << "B grade" << endl;
break;
case 'C' :
cout << "C grade" << endl;
break;
case 'D' :
cout << "D grade" << endl;
break;
case 'F' :
cout << "E grade" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;

return 0;
}

Output :

C grade
Your grade is C

Some rules of using Switch Statement :

The following rules apply to a switch statement:

1. Case Label must be unique

2. Case Labels must ends with Colon

3. Case labels must have constants / constant expression

4. Case label must be of integral Type ( Integer,Character)

5. Switch case should have at most one default label

6. Default label is Optional


7. Default can be placed anywhere in the switch

8. Break Statement takes control out of the switch

9. Two or more cases may share one break statement

10. Nesting ( switch within switch ) is allowed.

11. Relational Operators are not allowed in Switch Statement.

12. Macro Identifier are allowed as Switch Case Label.

13. Const Variable is allowed in switch Case Statement.

14. Empty Switch case is allowed.

C++ Nested If Statement

In C++ we can use if statement in the another else block. or we can also include if block in the
another if block.

Syntax : C++ Nested If

if( boolean_expression 1)
{
// Executes when the boolean expression 1 is true
if(boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
}

We can nest else ifelse in the similar way as you have nested if statement.

Example : Nested If-else

#include <iostream>
using namespace std;

int main ()
{
int marks = 55;
if( marks >= 80) {
cout << "U are 1st class !!";
}
else {
if( marks >= 60) {
cout << "U are 2nd class !!";
}
else {
if( marks >= 40) {
cout << "U are 3rd class !!";
}
else {
cout << "U are fail !!";
}
}
}
return 0;
}

Output :

U are 3rd class !!

C++ Functions
In order to perform some task, number of statements are grouped together. This group of statements
is called as function in C++ programming.

C++ Function :

1. Functions are written in order to make C++ program modular. We can break down the

complex program into the smaller chunks.

2. In C++ group of statements is given a particular name called function name. Function is

called from some point of the program

3. C++ program must have atleast 1 function and that function should be main.

Syntax of C++ Function Definition :

return_type function_name( parameter list )


{
body of the function
}

A C++ function definition consists of a function prototype declaration and a function body. All the
parts of a function are

Part Explanation

return_type is the type of data that function returns. It is not necessary


Return Type
that function will always return a value.

Function It is the actual name of the function. The function name and the parameter
Name list together forms the signature of the function

Parameters allow passing arguments to the function from the location


Parameters
where it is called from. Parameter list is separated by comma

Function The function body contains a collection of statements that define what the
Body function does.
We will explain all the parts of the function one by one

Function : Simple Example

#include <iostream>
using namespace std;

// function declaration
int sum(int num1, int num2);

int main ()
{
// local variable declaration:
int a = 10;
int b = 20;
int result;

// calling a function to get result.


result = sum(a, b);

cout << "Sum is : " << result << endl;

return 0;
}

// function returning the sum of two numbers


int sum(int num1, int num2)
{
// local variable declaration
int res;

res = num1 + num2;


return res;
}

Output :

Sum is : 30

Explanation :

We know that each and every C++ program starts with the main function. In the C++ main function
we have declared the local variable inside the function.

// local variable declaration:


int a = 10;
int b = 20;
int result;

Now after the declaration we need to call the function written by the user to calculate the sum of the
two numbers. So we are now calling the function by passing the two parameters.

result = sum(a, b);

Now function will evaluate the addition of the two numbers. After the addition of two numbers the
value will be returned to the calling function.Returned value will be assigned to the variable result.

C++ Array Basic


In the previous topic we have learnt about the functions in the C++ programming language. In this
tutorial we are looking for some basics of array.

C++ Array :
Suppose we need to store 100 roll numbers then we need to declare the 100 variables to keep track of
the 100 students. Accessing variables is also difficult in this case. All the variables are also stored at
random address in the memory.

Instead of declaring roll1,roll2,roll3. we can directly declare roll[100] in which


roll[1],roll[2].are considered as individual variables.

What is Array ?

1. Array is an data structure

2. Array is collection of elements of same data type or we can also say that array is collection of

variables of same type.

3. Array stores the elements in the sequential manner

4. Array elements are accessed randomly using the subscript or index variable

5. Array elements consist of contiguous memory locations.

6. Lowest address of an array corresponds to the first element.

7. Highest address of an array corresponds to the last element.

Recommanded Tutorial : What is subscript variable ?

Declaring Arrays:
In order to declare an array in C++, we need to specify the type of the elements and the number of
elements that we require

data-type arrayName [arraySize];

Suppose we need to declare the array of students then we can use


int roll[5]; // We created array of 5 students

In the above case we have 5 roll numbers

Element Description

roll[0] It represents variable for 1st roll number

roll[1] It represents variable for 2nd roll number

roll[2] It represents variable for 3rd roll number

roll[3] It represents variable for 4th roll number

roll[4] It represents variable for 5th roll number

Consider the below representation

Initializing Arrays:
Consider that we need to initialize array then we can initialize the array using the 3 ways.

Way 1 : Specify Size and initialize in 2 steps


In this case we declare the array in one line and initialization will be done using the loop.

int roll[5];
for(i=0;i<5;i++)
cin >> roll[i];
Way 2 : Specify Size and initialize in 1 step
In this case we declare and initialize array in single statement,

roll[5] = {11,22,33,44,55};

Here we have assigned following values to array element

Element Description

roll[0] 11

roll[1] 22

roll[2] 33

roll[3] 44

roll[4] 55

Way 3 : Without Specifying Size

In this case we just do assignment and initialization but compiler will automatically calculate the size
of the array at compile time.

roll[] = {11,22,33,44,55};

Above statement will specify the size of array equal to 5.

C++ Accessing Array :

#include <iostream>
using namespace std;

int main ()
{
// roll is an array of 10 integers
int roll[10];

// initialize elements of array


for (int i = 0; i < 10; i++) {
roll[i] = i + 1;
}

cout << "Element \t \t Value" << endl;

for (int i = 0; i < 10; i++) {


cout << i << "\t \t" << roll[i] << endl;
}

return 0;
}

Output :

Element Value
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
C++ Multi-dimensional Array

In the previous topic we have learnt about the basic concepts of array in C++. In this tutorial we are
looking for another type of an array called multi-dimensional array.

C++ Multi-dimensional Array :


In C++ we can create multidimensional array.Syntax to create multidimensional array is as below

data-type name[size1][size2]...[sizeN];

Suppose we need to create the 2-dimensional array then we can declare it as

int mat[5][4];

The above 2-dimensional array consists of the 5 rows and 4 columns.

Two-Dimensional Arrays:

1. Simplest form of the multidimensional array is the two-dimensional array.

2. 2-dimensional array is also called as matrix or table.

3. 2-dimensional array has 2 dimensions.

4. First dimension represents the number of row

5. Second dimension represents the number of columns.

Example of 2-dimensional array :


Consider the 2-dimensional array of size x,y then we can declare it like

data_type nameOfArray [ x ][ y ];

where

data_type will be any valid C++ data type


nameOfArray will be name of 2-dimensional array.
x will be number of rows
y will be number of columns

Representation :

Cell Location Meaning

a[0][0] 0th Row and 0th Column

a[0][1] 0th Row and 1st Column

a[0][2] 0th Row and 2nd Column

a[0][3] 0th Row and 3rd Column

a[1][0] 1st Row and 0th Column

a[1][1] 1st Row and 1st Column

a[1][2] 1st Row and 2nd Column

a[1][3] 1st Row and 3rd Column

a[2][0] 2nd Row and 0th Column

a[2][1] 2nd Row and 1st Column


Cell Location Meaning

a[2][2] 2nd Row and 2nd Column

a[2][3] 2nd Row and 3rd Column

Two-Dimensional Array : Summary with Sample Example

Summary Point Explanation

No of Subscript Variables Required 2

Declaration a[3][4]

No of Rows 3

No of Columns 4

No of Cells 12

No of for loops required to iterate 2

Initializing the 2-D array :

int a[3][2] = {
{ 1 , 4 }, /*Initialize 0th row*/
{ 5 , 2 }, /*Initialize 1st row*/
{ 6 , 5 } /*Initialize 2nd row*/
};

We can alternatively declare it as

int a[3][2] = {1,4,5,2,6,5};


C++ Pointer to an Array

C++ Pointer to an Array :

#include <iostream>
using namespace std;

int main ()
{
// an array with 5 elements.
double arr[5] = {10,20,30,40,50};
double *ptr;

ptr = arr;

// output each array element's value


cout << "Print Array Elements : " << endl;
for ( int i = 0; i < 5; i++ )
{
cout << "*(ptr + " << i << ") : ";
cout << *(ptr + i) << endl;
}

return 0;
}

Output :

Print Array Elements :


*(ptr + 0) : 10
*(ptr + 1) : 20
*(ptr + 2) : 30
*(ptr + 3) : 40
*(ptr + 4) : 50

Pictorial representation of the array is shown below

Explanation :

1. In the above example we have printed the elements of the array using the pointer.

2. Pointer is special type of variable which stores the address of the variable.

3. The base address of the array is assigned to the pointer variable using following statement.

ptr = arr;

Now consider the program in which we have assigned the starting address of array to pointer
variable.

Now we know that starting address of array is nothing but the address of first element

Main Logic behind Calculation :


Consider that we need to calculate the value of *(ptr + 4). It can be evaluated as

*(ptr + 4) = Value at (ptr + 4)


= Value at (ptr + 4 * Size of Data Type)
= Value at (ptr + 4 * 4)
= Value at (ptr + 16)
= Value at (1000 + 16)
= Value at (1016)
= 50

In the above calculation we have added 4 to pointer variable. Why we multiplied 4 with size of data
type ? See Re-commanded article

C++ Inheritance basics

In this chapter we will be learning about C++ Inheritance basics. Tutorial explains you different
types of inheritance in C++ programming language.

Basics of inheritance

Inheritance is one of the basic features of object oriented programming. In the process of inheritance,
one object can acquire the properties of another class.

Type of class Definition

A class that is inherited is called a base class. In below diagram, the


Base Class
class 'vehicle' is a base class.

The class that does the inheriting is called a derived class. In below
Derived Class
diagram, the class 'car' is a derived class.
Explanation

1. In the above picture, it is clearly mentioned that we are having two classes i.e base and

derived class.

2. Base class contains general information about the specific entity

3. Derived class contains more specific information related to the one of the type which is

inherited from the base class.

4. In above example vehicle class will contain general information about all vehicles but

derived class car contains all the information of the classvehicle along with car specific

information.

Types of Inheritance

According to the way of inheriting the properties of base class, there are certain forms of inheritance.
Inheritance Type #1 : Single Inheritance

In this type of inheritance, one Derived class is formed by acquiring the properties of one Base class.
Class Name Type Explanation

A Base class It is base class in the above program

B Derived class Class derives the properties of class A

Inheritance Type #2 : Multiple Inheritance

In this type of inheritance, one Derived class is formed by acquiring the properties of multiple Base
classes

Class Name Type Explanation

A Base class It is base class in the above program

B Base class It is base class in the above program

C Derived class Class derives the properties of class A and B

Inheritance Type #3 : Hierarchical Inheritance

In this type of inheritance, multiple subclass are formed by acquiring the properties of one Base
class.
Class Name Type Explanation

A Base class It is base class in the above program

B Derived class Class derives the properties of class A

C Derived class Class derives the properties of class A

D Derived class Class derives the properties of class A

Inheritance Type #4 : Multilevel Inheritance

In this type of inheritance, derived class is formed by acquiring the properties of one base class.

Again same derived class is used as a base class and another class is derived from this.
Class Name Type Explanation

A Base class It is base class in the above program

Base class for C and


B -
derived class for A

It contains all the properties of class A and B so


C Derived class
we can consider this as derived class of A also

Inheritance Type #5 : Hybrid Inheritance

In this type of Inheritance, the Derived class is formed by any legal combination of above four forms.
C++ Overloading assignment operator

We already know the assignment operator in C++. In this tutorial we will be learning concept of C++
Overloading assignment operator.

Assignment operator in C++

1. Assignment Operator is Used to assign value to an variable.

2. Assignment operator is denoted by equal to sign.


3. Assignment operator have Two values L-Value and R-value. Operator copies R-Value into

L-Value.

4. It is a binary operator.

C++ Overloading Assignment Operator

1. C++ Overloading assignment operator can be done in object oriented programming.

2. By overloading assignment operator, all values of one object (i.e instance variables) can be

copied to another object.

3. Assignment operator must be overloaded by a non-static member function only.

4. If the overloading function for the assignment operator is not written in the class, the

compiler generates the function to overload the assignment operator.

Syntax

Return_Type operator = (const Class_Name &)

Way of overloading Assignment Operator

#include<iostream>
using namespace std;

class Marks
{
private:
int m1;
int m2;

public:

//Default constructor
Marks() {
m1 = 0;
m2 = 0;
}

// Parametrised constructor
Marks(int i, int j) {
m1 = i;
m2 = j;
}

// Overloading of Assignment Operator


void operator=(const Marks &M ) {
m1 = M.m1;
m2 = M.m2;
}

void Display() {
cout << "Marks in 1st Subject:" << m1;
cout << "Marks in 2nd Subject:" << m2;
}
};

int main()
{
// Make two objects of class Marks
Marks Mark1(45, 89);
Marks Mark2(36, 59);

cout << " Marks of first student : ";


Mark1.Display();
cout << " Marks of Second student :";
Mark2.Display();

// use assignment operator


Mark1 = Mark2;

cout << " Mark in 1st Subject :";


Mark1.Display();

return 0;
}

Explanation

private:
int m1;
int m2;

Here, in Class Marks contains private Data Members m1 and m2.

Marks Mark1(45, 89);


Marks Mark2(36, 59);

In the main function, we have made two objects Mark1 and Mark2 of class Marks. We have
initialized values of two objects using parametrised constructor.

void operator=(const Marks &M ) {


m1 = M.m1;
m2 = M.m2;
}

As shown in above code, we overload the assignment operator, Therefore, Mark1=Mark2 from
main function will copy content of object Mark2 into Mark1.

Output

Marks of first student :


Mark in 1st Subject : 45
Marks in 2nd Subject : 89

Marks of Second student :


Mark in 1st Subject : 36
Marks in 2nd Subject : 59

Marks of First student :


Mark in 1st Subject : 36
Marks in 2nd Subject : 59

C++ Constructor basic concept

In this tutorial we will learnt about C++ constructor basic concept. Tutorial explains you everything
about constructor in C++ in easier language.

C++ Constructor basic concept

1. C++ constructors are the special member function of the class which are used to initialize the

objects of that class

2. The constructor of class is automatically called immediately after the creation of the object.

3. Name of the constructor should be exactly same as that of name of the class.

4. C++ constructor is called only once in a lifetime of object when object is created.

5. C++ constructors can be overloaded

6. C++ constructors does not return any value so constructor have no return type.

7. C++ constructor does not return even void as return type.

C++ Constructor Types

1. Default Constructor

2. Parametrized Constructor
3. Copy Constructor

We will discuss different C++ constructor types in detail

C++ Constructor Types #1 : Default Constructor

1. If the programmer does not specify the constructor in the program then compiler provides the

default constructor.

2. In C++ we can overload the default compiler generated constructor

3. In both cases (user created default constructor or default constructor generated by compiler),

the default constructor is always parameterless.

Syntax

class_name() {
-----
-----
}

Example of Default Constructor

Let us take the example of class Marks which contains the marks of two subjects Maths and Science.

#include<iostream>
using namespace std;

class Marks
{
public:
int maths;
int science;

//Default Constructor
Marks() {
maths=0;
science=0;
}

display() {
cout << "Maths : " << maths <<endl;
cout << "Science :" << science << endl;
}
};

int main() {
//invoke Default Constructor
Marks m;
m.display();
return 0;
}

Output :

Maths : 0
Science : 0

C++ Constructor Types #2 : Parametrized Constructor

This type of constructor can take the parameters.

Syntax

class_name(Argument_List) {
-----
-----
}

Example of Parametrized Constructor

Let us take the example of class Marks which contains the marks of two subjects Maths and
Science.

#include<iostream>
using namespace std;

class Marks
{
public:
int maths;
int science;

//Parametrized Constructor
Marks(int mark1,int mark2) {
maths = mark1;
science = mark2;
}

display() {
cout << "Maths : " << maths <<endl;
cout << "Science :" << science << endl;
}
};

int main() {
//invoke Parametrized Constructor
Marks m(90,85);
m.display();
return 0;
}

Output

Maths : 90
Science : 85
C++ Constructor Types #3 : Copy Constructor

1. All member values of one object can be assigned to the other object using copy constructor.

2. For copying the object values, both objects must belong to same class.

Syntax

class_Name (const class_Name &obj) {


// body of constructor
}

Example of Copy Constructor

Let us take the example of class Marks which contains the marks of two subjects Maths and
Science.

#include<iostream>
using namespace std;

class marks
{
public:
int maths;
int science;

//Default Constructor
marks(){
maths=0;
science=0;
}

//Copy Constructor
marks(const marks &obj){
maths=obj.maths;
science=obj.science;
}
display(){
cout<<"Maths : " << maths
cout<<"Science : " << science;
}
};

int main(){
marks m1;

/*default constructor gets called


for initialization of m1 */
marks m2(const marks &m1);

//invoke Copy Constructor


m2.display();

return 0;
}

Output

Maths : 0
Science : 0

C++ Relational Operators

C++ Relational operators specify the relation between two variables by comparing them. There are 5
relational operators in C
C++ Relational Operators

In C++ Programming, the values stored in two variables can be compared using following operators
and relation between them can be determined.

Various C++ relational operators available are-

Operator, Meaning
> ,Greater than
>= , Greater than or equal to
== , Is equal to
!= , Is not equal to
< , Less than or equal to <= , Less than [/table]

Relational Operator Programs


Program #1: Relational Operator Comparison

As we discussed earlier, C++ Relational Operators are used to compare values of two variables. Here
in example we used the operators in if statement.

Now if the result after comparison of two variables is True, then if statementreturns value 1.

And if the result after comparison of two variables is False, then if statementreturns value 0.

#include<iostream>
using namespace std;

int main()
{
int a=10,b=20,c=10;

if(a>b)
cout<<"a is greater"<<endl;

if(a<b)
cout<<"a is smaller"<<endl;

if(a<=c)
cout<<"a is less than/equal to c"<<endl;

if(a>=c)
cout<<"a is less than/equal to c"<<endl;

return 0;
}

Output

a is smaller
a is less than/equal to c
a is greater than/equal to c

Program #2: Relational Operator Equality

In C++ Relational operators, two operators that is == (Is Equal to) and != (is Not Equal To), are used
to check whether the two variables to be compared are equal or not.

Let us take one example which demonstrate this two operators.

#include<iostream>
using namespace std;

int main()
{
int num1 = 30;
int num2 = 40;
int num3 = 40;

if(num1!=num2)
cout<<"num1 Is Not Equal To num2"<<endl;

if(num2==num3)
cout<<"num2 Is Equal To num3"<<endl;
return(0);
}

Output

num1 Is Not Equal To num2


num2 Is Equal To num3

Get in Touch!
C++ Logical Operator

In this tutorial we will study C++ logical operator in detail. C++ logical operators are used mostly
inside the condition statement such as if,ifelse where we want multiple conditions.

C++ Logical Operator

1. Logical Operators are used if we want to compare more than one condition.

2. Depending upon the requirement, proper logical operator is used.

3. Following table shows us the different C++ operators available.

Operators Name of the Operator Type

&& AND Operator Binary


Operators Name of the Operator Type

|| OR Operator Binary

! NOT Operator Unary

According to names of the Logical Operators, the condition satisfied in following situation and
expected outputs are given

Operator Output

AND Output is 1 only when conditions on both sides of Operator become True

OR Output is 0 only when conditions on both sides of Operator become False

NOT It gives inverted Output

Let us look at all logical operators with example-

C++ Program : Logical Operator

#include<iostream>
using namespace std;

int main()
{
int num1=30;
int num2=40;

if(num1>=40 || num2>=40)
cout<<"OR If Block Gets Executed"<<endl;

if(num1>=20 && num2>=20)


cout<<"AND If Block Gets Executed"<<endl;
if(!(num1>=40))
cout<<"NOT If Block Gets Executed"<<endl;

return 0;
}

Output:

OR If Block Gets Executed


AND If Block Gets Executed
NOT If Block Gets Executed

Explanation of the Program

Or statement gives output = 1 when any of the two condition is satisfied.

if(num1>40 || num2>=40)

Here in above program , num2=40. So one of the two conditions is satisfied. So statement is
executed.

For AND operator, output is 1 only when both conditions are satisfied.

if(num1>=20 && num2>=20)

Thus in above program, both the conditions are True so if block gets executed.

Truth table

Operator 1st Condition 2nd Condition Output

AND True True True

True False False

False True False


Operator 1st Condition 2nd Condition Output

False False False

OR True True True

True False True

False True True

False False False

NOT True False

False True

C++ Assignment Operator

C++ assignment Operator basics

1. Assignment Operator is used to assign value to an variable.

2. Assignment Operator is denoted by equal to (=) sign.

3. This operator copies the value at the right side of the operator into the left side variable.

4. Assignment Operator is binary operator.

5. Assignment Operator has higher precedence than comma operator only.

6. Assignment Operator has lower precedence than all other operators except comma operator.
Ways of Using Assignment Operator:

In this section we are going to see different ways in which Assignment Operator can be used.

Assignment Operator used to Assign Value

In this case the particular value or result of particular expression is assigned to the variable.

#include<iostream>
using namespace std;

int main()
{
int value;
value=10;
return 0;
}

In this example, 10 is assigned to variable value.

Assignment Operator used to Type Cast

#include<iostream>
using namespace std;

int main()
{
int value;
value=10.5;
cout<<value;
return 0;
}

Higher values can be type cast to lower values using assignment operator. It can also cast lower
values to higher values.

Shorthand assignment operator:


Operator Symbol Name of Operator Example Equivalent Construct

+= Addition assignment a+=5 a=a+5

-= Subtraction assignment a-=5 a=a-5

*= Multiplication assignment a*=5 a=a*5

/= Division assignment a/=5 a=a/5

%= Remainder assignment a%=5 a=a%5

Example:

#include <iostream>
using namespace std;

int main()
{
int num = 10;
num+=5 ;
cout << "Result of Expression 1 = " <<num<< endl ;

num = 10;
num-=5 ;
cout << "Result of Expression 2 = " <<num<< endl ;

num = 10;
num*=5 ;
cout << "Result of Expression 3 = " <<num<< endl ;

num = 10;
num/=5 ;
cout << "Result of Expression 4 = " <<num<< endl ;

num = 10;
num%=5 ;
cout << "Result of Expression 5 = " <<num<< endl ;

return 0;
}

Output:

Result of Expression 1 = 15
Result of Expression 2 = 5
Result of Expression 3 = 50
Result of Expression 4 = 2
Result of Expression 5 = 0

C++ Destructor Basics

In the previous chapter we have learnt about the C++ constructors and basic type of constructors. In
this chapter we will be learning about C++ Destructor Basics

C++ Destructor Basics


1. Destructors are special member functions of the class required to free the memory of the

object whenever it goes out of scope.

2. Destructors are parameterless functions.

3. Name of the Destructor should be exactly same as that of name of the class. But preceded by

~ (tilde).

4. Destructors does not have any return type. Not even void.

5. The Destructor of class is automatically called when object goes out of scope.

C++ Destructor programs


C++ Destructor Program #1 : Simple Example

#include<iostream>
using namespace std;

class Marks
{
public:
int maths;
int science;

//constructor
Marks() {
cout << "Inside Constructor"<<endl;
cout << "C++ Object created"<<endl;
}

//Destructor
~Marks() {
cout << "Inside Destructor"<<endl;
cout << "C++ Object destructed"<<endl;
}
};
int main( )
{
Marks m1;
Marks m2;
return 0;
}

Output

Inside Constructor
C++ Object created
Inside Constructor
C++ Object created

Inside Destructor
C++ Object destructed
Inside Destructor
C++ Object destructed

Explanation :

You can see destructor gets called just before the return statement of main function. You can see
destructor code below

~Marks() {
cout << "Inside Destructor"<<endl;
cout << "C++ Object destructed"<<endl;
}

C++ Destructor always have same name as that of constructor but it just identified by tilde (~)
symbol before constructor name.

Below example will show you how C++ destructor gets called just before C++ object goes out of
scope.
C++ Destructor Program #2 : Out of scope

#include<iostream>
using namespace std;

class Marks
{
public:
int maths;
int science;

//constructor
Marks() {
cout << "Inside Constructor"<<endl;
cout << "C++ Object created"<<endl;
}

//Destructor
~Marks() {
cout << "Inside Destructor"<<endl;
cout << "C++ Object destructed"<<endl;
}
};

int main( )
{
{
Marks m1;
}

cout<<"Hello World !!" <<endl;


cout<<"Hello World !!" <<endl;
cout<<"Hello World !!" <<endl;
cout<<"Hello World !!" <<endl;
return 0;
}

Output :

Inside Constructor
C++ Object created
Inside Destructor
C++ Object destructed

Hello World !!
Hello World !!
Hello World !!
Hello World !!

Explanation :

In this example we have defined the scope of the object as we declared object inside the curly braces
i.e inside the inner block.

int main( )
{
{
Marks m1;
}

So object will be accessible only inside the curly block. Outside the curly block we cannot access the
object so destructor gets called when inner curly block ends

In this example Hello World !! gets printed after the destructor. however for below example Hello
World !! gets printed before constructor

C++ Destructor Program #3 : before destructor

#include<iostream>
using namespace std;
class Marks
{
public:
int maths;
int science;

//constructor
Marks() {
cout << "Inside Constructor"<<endl;
cout << "C++ Object created"<<endl;
}

//Destructor
~Marks() {
cout << "Inside Destructor"<<endl;
cout << "C++ Object destructed"<<endl;
}
};

int main( )
{
Marks m1;

cout<<"Hello World !!" <<endl;


cout<<"Hello World !!" <<endl;
cout<<"Hello World !!" <<endl;
cout<<"Hello World !!" <<endl;

return 0;
}

Output :

Inside Constructor
C++ Object created

Hello World !!
Hello World !!
Hello World !!
Hello World !!

Inside Destructor
C++ Object destructed

C++ sizeof Operator

C++ sizeof Operator

sizeof is a compile-time operator used to calculate the size of data type or variable.
sizeof operator will return the size in integer format.
sizeof is a keyword.
sizeof operator can be nested.

Syntax of sizeof Operator:

sizeof(data type)

Data type include variables, constants, classes, structures, unions, or any other user defined data type.

Examples of sizeof operator:


Size of Data Types

#include <iostream>
using namespace std;
int main()
{
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of char : " << sizeof(char) << endl;

return 0;
}

Output:

Size of int : 4
Size of long int : 4
Size of float : 4
Size of double : 8
Size of char : 1

Size of Variables:

#include <iostream>
using namespace std;

int main()
{
int i;
char c;

cout << "Size of variable i : " << sizeof(i) << endl;


cout << "Size of variable c : " << sizeof(c) << endl;

return 0;
}

Output:

Size of variable i : 4
Size of variable c : 1

Size of Constant:

#include <iostream>
using namespace std;

int main()
{
cout << "Size of integer constant: " << sizeof(10) << endl;
cout << "Size of character constant : " << sizeof('a') << endl;

return 0;
}

Output:

Size of integer constant: 4


Size of character constant : 1

Nested sizeof operator:

#include <iostream>
using namespace std;

int main()
{
int num1,num2;
cout << sizeof(num1*sizeof(num2));
return 0;
}
Output:

C++ Conditional Operator

Conditional Operator [?:] : Ternary Operator in C++

1. Conditional operators are also called as Ternary Operator.

2. They are represented by ?:

3. Ternary Operator takes on 3 Arguments.

Syntax of Ternary Operator:

Expression_1 ? Expression_2 : Expression_3

where

Expression_1 is Condition

Expression_2 is statement followed if Condition is True

Expression_3 is statement followed if Condition is False

Explanation of syntax:

1. Expression_1 is a condition so it will return the result either True or False.

2. If result of expression_1 is True that is NON-ZERO, then Expression_2 is Executed.


3. If result of expression_1 is False that is ZERO, then Expression_3 is Executed.

Program 1#: Conditional Operator Program

Let us take the simple example of finding greater number from two given numbers using Conditional
Operator.

#include<iostream>
using namespace std;

int main()
{
int num1=10;
int num2=20;

num1>num2 ? cout << "num1 is greater than num2" : cout<< "num2 is greater than
num1" ;

return 0;
}

Output:

num2 is greater than num1

C++ Pointer Operator


In this chapter we are going to study C++ Pointer Operators. C++ provides two pointer operators one
is value at operator or indirection operator and address operator.

C++ Pointer Operator

C++ Address of Operator (&)

1. The & is a unary operator means it requires only one operand.

2. The Address of Operator returns the memory address of its operand.

3. Address of operator has the same precedence and right-to-left associativity as that of other

unary operators.

4. Symbol for the bitwise AND and the address of operator are the same but they dont have

any connection between them


C++ Program : Address of Operator

#include<iostream>
using namespace std;

int main()
{
int num=10;

cout << "Value of number : " << num << endl;


cout << "Address of number : " << &num << endl;
}

Output :

Value of number : 10
Address of number : 0xffad72dc

Summary

Point Explanation

Operator Address of

Type Unary Operator

Operates on Single Operand

Returns Address of the operand

Associativity right-to-left

Explanation Address of operator gives the computer's internal location of the variable.

C++ Indirection Operator *


1. The Indirection operator * is a unary operator means it requires only one operand.

2. Indirection Operator (*) is the complement of Address of Operator (&).

3. Indirection Operator returns the value of the variable located at the address specified by its

operand.

C++ Program : Indirection Operator

#include<iostream>
using namespace std;

int main()
{
int num=10;
int *ptr;

ptr=&num;

cout << " num = " << num << endl;


cout << " &num = " << &num << endl;
cout << " ptr = " << ptr << endl;
cout<< " *ptr = " << *ptr << endl;
}

Output :

num = 10
&num = 0xffcc2bd8
ptr = 0xffcc2bd8
*ptr = 10

Calculations:

// Sample Code for Dereferencing of Pointer

*(ptr) = value at (ptr)


= value at (0xffcc2bd8)
= 10

//Address in ptr is nothing but address of num

Summary

Point Explanation

Operator Indirection Operator

Type Unary Operator

Operates on Single Operand

Returns Value at address of the operand)

Associativity right-to-left

Though multiplication symbol and the Indirection Operator symbol are the same still they dont
have any relationship between each other.

Both & and * have a higher precedence than all other arithmetic operators except the unary
minus/plus, with which they share equal precedence.

You might also like