C New
C New
Background History :
2. During the creation of Ph.D. thesis, Bjarne Stroustrup worked with language called Simula.
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
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
2. In the early 1980s, also at Bell Laboratories, another programming language was created
4. Stroustrup states that the purpose of C++ is to make writing good programs easier and more
Creator of C++
1. Visual C++
2. Borland 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
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
3. Byte Code i.e intermediate code is executed by the Run Time Environment.
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
..
/*
This is a simple C++ program.
Call this file Sample.cpp.
*/
#include <iostream>
using namespace std;
Output :
/*
This is a simple C++ program.
Call this file Sample.cpp.
*/
1. It is Comment in C++ Language which is ignored by compiler
#include <iostream>
4. Include statement tells compiler to include Standard Input Output Stream inside C++
program.
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
enever some error or exception occurs in the program then main function will return the non zero
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
2. The name C++ comes from the C increment operator ++, which adds 1 to the value of a
variable.
5. C++ supports for the Structured programming and also it fully supportsOOP
1. Encapsulation
2. Data hiding
3. Inheritance
4. Polymorphism.
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 Intermediate-level language,
11. Most of the C++ concepts are considered as basic concepts for Java Programming.
o is a better C
.
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
3. Dev C++
4. GCC
5. Eclipse
,,,,,,,,,,,,,,,
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
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.
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.
C++ Comments
cout<<"www.c4learn.com"; //Website
int main()
{
/* this comment
can be considered
as
multiple line comment */
return(0);
}
int main()
{
return(0);
}
Above comment is used for documentation. We use This type of Documentation to summarize C++
code.
<script type="text/javascript">
// document.write("<h1>Heading</h1>");
document.write("<p>Google</p>");
document.write("<p>Yahoo</p>");
</script>
// document.write("<h1>Heading</h1>");
int main()
{
person p1,p2;
p1.getData();
p2.putData();
// p3.getData();
return(0);
}
int main()
{
person p1,p2;
p1.getData(); // Get Personal Info
p2.putData(); // Save Personal Info
return(0);
}
int main()
{
int age=0;
//initialize age to 0
return(0);
}
.
C++ cin
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.
#include<iostream.h>//traditional C++
OR
int main()
{
int number1;
int number2;
cout<<"Addition : ";
cout<<number1+number2; //Display Addition
return 0;
}
Output :
int tempNumber;
cin >> tempNumber;
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).
C++ cout
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.
#include<iostream.h>//traditional C++
OR
#include<iostream.h>
using namespace std;
int main()
{
int number1;
int number2;
cin>>number1;
cin>>number2;
cout<<"Addition : ";
cout<<number1+number2; //Display Result
return 0;
}
Output :
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.
int a=10;
int b=20;
cout << a << b;
is similar to
int a=10;
int b=20;
cout << a;
cout << b;
or
int num1;
int num2;
or
Output :
Hello,
My name is
Pooja...
4. setw() sets the number of characters to be used as the field width for the next insertion operation.
Syntax :
setw(num)
#include <iostream>
#include <iomanip>
return 0;
}
#include <iostream>
#include <iomanip>
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
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
4. C++ can be used for developing System Software viz., operating systems, compilers, editors
5. C++ is suitable for Development of Reusable Software. , thus reduces cost of software
development.
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)
Identifier Note
Identifier Explanation
int Keyword name cannot be given to Variable/Identifier
Token Example
Digits 0-9
The following table will depict the characters used in C++ Progeamming language
Brackets (){}[]
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.
Term Definition
Special
ASCII printable characters are called as Special Characters
Character
..
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++ :
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
2. The name of identifier cannot begin with a digit. However, Underscore can be used as first
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
C++ Keywords
In C++, keywords are reserved identifiers which cannot be used as names for the variables in a
program.
C++ Constants
Constants are the items whose value cannot be changed during the program execution.
C++ Constants :
Type of
Explanation
Constant
Character
These are alphabets i.e A-Z or a-z
Constant
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
Logical Operators Used for identifying the truth value of the expression
Misc Operators -
Arithmetic Operators :
one
Relational Operators:
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 :
Logical AND If both the operands are non-zero then only (A && B) is
(&&) condition becomes true false.
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
3. True condition can be any non-zero number and Zero is considered as false condition
while(condition)
{
statement(s);
}
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration
int num = 5;
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.
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.
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++;
}
In the previous chapter we have already seen the while loop in C++programming language.
#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
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
3. In the third step of the execution of for-loop, the update expression is evaluated.
#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.
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
do
{
statement(s);
}while( condition );
#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
do-while While
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.
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.
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)
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.
#include <iostream>
using namespace std;
int main ()
{
int i, j;
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
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;
#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.
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.
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.
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
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
int main ()
{
int count = 0;
do
{
count++;
if(count > 5 && count < 7)
continue;
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.
A goto statement used as unconditional jump from the goto to a labeled statement in the same
function.
Syntax :
goto label;
..
.
label: statement;
#include <iostream>
using namespace std;
int main ()
{
int num = 1;
STEP:do
{
if( num == 5)
{
num = num + 1;
goto STEP;
}
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
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(boolean_expression)
{
// statement(s) will execute if the
// boolean expression is true
}
#include <iostream>
using namespace std;
int main ()
{
// Declaring local variable
int num = 5;
return 0;
}
Output :
In the above program, In the if condition we are checking the following condition
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.
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 block sometimes followed with the optional else block. When the if condition becomes false then
else block gets executed.
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 :
#include <iostream>
using namespace std;
int main ()
{
// declare local variable
int marks = 30;
Output :
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
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.
#include <iostream>
using namespace std;
int main ()
{
// declare local variable
int marks = 55;
return 0;
}
Output :
Explanation :
1. Firstly condition 1 specified in the if statement is checked. In this case the condition becomes
2. Now 2nd block condition also evaluates to be false then again the 2nd block will be skipped
3. In the above example the condition specified in the 3rd block evaluates to be true so the third
Flowchart diagram :
Some rules of using else if ladder in C++ :
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++ 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
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
In C++ we can use if statement in the another else block. or we can also include if block in the
another if block.
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.
#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 :
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
2. In C++ group of statements is given a particular name called function name. Function is
3. C++ program must have atleast 1 function and that function should be main.
A C++ function definition consists of a function prototype declaration and a function body. All the
parts of a function are
Part Explanation
Function It is the actual name of the function. The function name and the parameter
Name list together forms the signature of the function
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
#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;
return 0;
}
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.
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.
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 :
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.
What is Array ?
2. Array is collection of elements of same data type or we can also say that array is collection of
4. Array elements are accessed randomly using the subscript or index 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
Element Description
Initializing Arrays:
Consider that we need to initialize array then we can initialize the array using the 3 ways.
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};
Element Description
roll[0] 11
roll[1] 22
roll[2] 33
roll[3] 44
roll[4] 55
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};
#include <iostream>
using namespace std;
int main ()
{
// roll is an array of 10 integers
int roll[10];
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.
data-type name[size1][size2]...[sizeN];
int mat[5][4];
Two-Dimensional Arrays:
data_type nameOfArray [ x ][ y ];
where
Representation :
Declaration a[3][4]
No of Rows 3
No of Columns 4
No of Cells 12
int a[3][2] = {
{ 1 , 4 }, /*Initialize 0th row*/
{ 5 , 2 }, /*Initialize 1st row*/
{ 6 , 5 } /*Initialize 2nd row*/
};
#include <iostream>
using namespace std;
int main ()
{
// an array with 5 elements.
double arr[5] = {10,20,30,40,50};
double *ptr;
ptr = arr;
return 0;
}
Output :
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
In the above calculation we have added 4 to pointer variable. Why we multiplied 4 with size of data
type ? See Re-commanded article
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.
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.
3. Derived class contains more specific information related to the one of the type which is
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
In this type of inheritance, one Derived class is formed by acquiring the properties of multiple Base
classes
In this type of inheritance, multiple subclass are formed by acquiring the properties of one Base
class.
Class Name Type Explanation
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
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.
L-Value.
4. It is a binary operator.
2. By overloading assignment operator, all values of one object (i.e instance variables) can be
4. If the overloading function for the assignment operator is not written in the class, the
Syntax
#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;
}
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);
return 0;
}
Explanation
private:
int m1;
int m2;
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.
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
In this tutorial we will learnt about C++ constructor basic concept. Tutorial explains you everything
about constructor in C++ in easier language.
1. C++ constructors are the special member function of the class which are used to initialize the
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.
6. C++ constructors does not return any value so constructor have no return type.
1. Default Constructor
2. Parametrized Constructor
3. Copy Constructor
1. If the programmer does not specify the constructor in the program then compiler provides the
default constructor.
3. In both cases (user created default constructor or default constructor generated by compiler),
Syntax
class_name() {
-----
-----
}
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
Syntax
class_name(Argument_List) {
-----
-----
}
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
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;
return 0;
}
Output
Maths : 0
Science : 0
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.
Operator, Meaning
> ,Greater than
>= , Greater than or equal to
== , Is equal to
!= , Is not equal to
< , Less than or equal to <= , Less than [/table]
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
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.
#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
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.
1. Logical Operators are used if we want to compare more than one condition.
|| OR Operator Binary
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
#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;
return 0;
}
Output:
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.
Thus in above program, both the conditions are True so if block gets executed.
Truth table
False True
3. This operator copies the value at the right side of the operator into the left side variable.
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.
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;
}
#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.
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
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
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.
#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;
}
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
#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;
return 0;
}
Output :
Inside Constructor
C++ Object created
Hello World !!
Hello World !!
Hello World !!
Hello World !!
Inside Destructor
C++ Object destructed
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.
sizeof(data type)
Data type include variables, constants, classes, structures, unions, or any other user defined data type.
#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;
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:
#include <iostream>
using namespace std;
int main()
{
int num1,num2;
cout << sizeof(num1*sizeof(num2));
return 0;
}
Output:
where
Expression_1 is Condition
Explanation of syntax:
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:
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
#include<iostream>
using namespace std;
int main()
{
int num=10;
Output :
Value of number : 10
Address of number : 0xffad72dc
Summary
Point Explanation
Operator Address of
Associativity right-to-left
Explanation Address of operator gives the computer's internal location of the variable.
3. Indirection Operator returns the value of the variable located at the address specified by its
operand.
#include<iostream>
using namespace std;
int main()
{
int num=10;
int *ptr;
ptr=#
Output :
num = 10
&num = 0xffcc2bd8
ptr = 0xffcc2bd8
*ptr = 10
Calculations:
Summary
Point Explanation
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.