You are on page 1of 104

Explicit type conversion

Conversions that require user intervention to change the data type of one
variable to another, is called the explicit type conversion. In other words, an
explicit conversion allows the programmer to manually changes or typecasts
the data type from one variable to another type. Hence, it is also known as
typecasting. Generally, we force the explicit type conversion to convert data
from one type to another because it does not follow the implicit conversion
rule.

The explicit type conversion is divided into two ways:

1. Explicit conversion using the cast operator


2. Explicit conversion using the assignment operator

Program to convert float value into int type using the cast operator

Cast operator: In C++ language, a cast operator is a unary operator who


forcefully converts one type into another type.

Let's consider an example to convert the float data type into int type using the
cast operator of the explicit conversion in C++ language.

Program3.cpp

1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5. float f2 = 6.7;
6. // use cast operator to convert data from one type to another
7. int x = static_cast <int> (f2);
8. cout << " The value of x is: " << x;
9. return 0;
10.}

Output

The value of x is: 6

 Converting by assignment: This is done by explicitly defining the required


type in front of the expression in parenthesis. This can be also considered
as forceful casting.
Syntax:
(type) expression
where type indicates the data type to which the final result is converted.
Example:

// C++ program to demonstrate

// explicit type casting

#include <iostream>

using namespace std;

int main()

double x = 1.2;

// Explicit conversion from double to int

int sum = (int)x + 1;

cout << "Sum = " << sum;

return 0;

Output:
Sum = 2
C++ Variables
Variables in C++ is a name given to a memory location. It is the basic unit of
storage in a program.
 The value stored in a variable can be changed during program execution.
 A variable is only a name given to a memory location, all the operations
done on the variable effects that memory location.
 In C++, all the variables must be declared before use.
Rules For Declaring Variable
1. The name of the variable contains letters, digits, and underscores.
2. The name of the variable is case sensitive (ex Arr and arr both are different
variables).
3. The name of the variable does not contain any whitespace and special
characters (ex #,$,%,*, etc).
4. All the variable names must begin with a letter of the alphabet or
an underscore(_).
5. We cannot used C++ keyword(ex float,double,class)as a variable name.
How to Declare Variables?
A typical variable declaration is of the form:
// Declaring a single variable
type variable_name;

// Declaring multiple variables:


type variable1_name, variable2_name, variable3_name;
A variable name can consist of alphabets (both upper and lower case),
numbers, and the underscore ‘_’ character. However, the name must not start
with a number.

Initialization of a variable in C++

In the above diagram,


Advertisement

datatype: Type of data that can be stored in this variable.


variable_name: Name given to the variable.
value: It is the initial value stored in the variable.
Examples:
// Declaring float variable
float simpleInterest;
// Declaring integer variable
int time, speed;

// Declaring character variable


char var;
Difference Between Variable Declaration and Definition
The variable declaration refers to the part where a variable is first declared or
introduced before its first use. A variable definition is a part where the
variable is assigned a memory location and a value. Most of the time, variable
declaration and definition are done together.
See the following C++ program for better clarification:
 C++

// C++ program to show difference between

// definition and declaration of a

// variable

#include <iostream>

using namespace std;

int main()

// this is declaration of variable a

int a;

// this is initialisation of a

a = 10;

// this is definition = declaration + initialisation


int b = 20;

// declaration and definition

// of variable 'a123'

char a123 = 'a';

// This is also both declaration and definition

// as 'c' is allocated memory and

// assigned some garbage value.

float c;

// multiple declarations and definitions

int _c, _d45, e;

// Let us print a variable

cout << a123 << endl;

return 0;

Output

a
Time Complexity: O(1)
Space Complexity: O(1)
Types of Variables
There are three types of variables based on the scope of variables in C++
 Local Variables
 Instance Variables
 Static Variables
Types of Variables in C++

Let us now learn about each one of these variables in detail.


1. Local Variables: A variable defined within a block or method or constructor
is called a local variable.
 These variables are created when entered into the block or the function
is called and destroyed after exiting from the block or when the call
returns from the function.
 The scope of these variables exists only within the block in which the
variable is declared. i.e. we can access this variable only within that
block.
 Initialization of Local Variable is Mandatory.

2. Instance Variables: Instance variables are non-static variables and are


declared in a class outside any method, constructor, or block.
 As instance variables are declared in a class, these variables are created
when an object of the class is created and destroyed when the object is
destroyed.
 Unlike local variables, we may use access specifiers for instance
variables. If we do not specify any access specifier then the default
access specifier will be used.
 Initialization of Instance Variable is not Mandatory.
 Instance Variable can be accessed only by creating objects.

3. Static Variables: Static variables are also known as Class variables.


 These variables are declared similarly as instance variables, the
difference is that static variables are declared using the static
keyword within a class outside any method constructor or block.
 Unlike instance variables, we can only have one copy of a static variable
per class irrespective of how many objects we create.
 Static variables are created at the start of program execution and
destroyed automatically when execution ends.
 Initialization of Static Variable is not Mandatory. Its default value is 0
 If we access the static variable like the Instance variable (through an
object), the compiler will show the warning message and it won’t halt
the program. The compiler will replace the object name with the class
name automatically.
 If we access the static variable without the class name, the Compiler will
automatically append the class name.

Instance Variable Vs Static Variable


 Each object will have its own copy of the instance variable whereas We
can only have one copy of a static variable per class irrespective of how
many objects we create.
 Changes made in an instance variable using one object will not be
reflected in other objects as each object has its own copy of the instance
variable. In the case of static, changes will be reflected in other objects as
static variables are common to all objects of a class.
 We can access instance variables through object references and Static
Variables can be accessed directly using the class name.
 The syntax for static and instance variables:
class Example
{
static int a; // static variable
int b; // instance variable
}

C++ Expression

C++ expression consists of operators, constants, and variables which are


arranged according to the rules of the language. It can also contain function
calls which return values. An expression can consist of one or more operands,
zero or more operators to compute a value. Every expression produces some
value which is assigned to the variable with the help of an assignment
operator.

Examples of C++ expression:

1. (a+b) - c
2. (x/y) -z
3. 4a2 - 5b +c
4. (a+b) * (x+y)

An expression can be of following types:


o Constant expressions
o Integral expressions
o Float expressions
o Pointer expressions
o Relational expressions
o Logical expressions
o Bitwise expressions
o Special assignment expressions

If the expression is a combination of the above expressions, such expressions


are known as compound expressions.

Constant expressions

A constant expression is an expression that consists of only constant values. It


is an expression whose value is determined at the compile-time but evaluated
at the run-time. It can be composed of integer, character, floating-point, and
enumeration constants.
o It is used in the subscript declarator to describe the array bound.
o It is used after the case keyword in the switch statement.
o It is used as a numeric value in an enum
o It specifies a bit-field width.
o It is used in the pre-processor #if

In the above scenarios, the constant expression can have integer, character,
and enumeration constants. We can use the static and extern keyword with the
constants to define the function-scope.

The following table shows the expression containing constant value:

Expression containing constant Constant value

x = (2/3) * 4 (2/3) * 4

extern int y = 67 67

int z = 43 43

static int a = 56 56

Let's see a simple program containing constant expression:

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x; // variable declaration.
6. x=(3/2) + 2; // constant expression
7. cout<<"Value of x is : "<<x; // displaying the value of x.
8. return 0;
9. }

In the above code, we have first declared the 'x' variable of integer type. After
declaration, we assign the simple constant expression to the 'x' variable.

Output
Value of x is : 3

Integral Expressions

An integer expression is an expression that produces the integer value as


output after performing all the explicit and implicit conversions.

Following are the examples of integral expression:

1. (x * y) -5
2. x + int(9.0)
3. where x and y are the integers.

Let's see a simple example of integral expression:

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x; // variable declaration.
6. int y; // variable declaration
7. int z; // variable declaration
8. cout<<"Enter the values of x and y";
9. cin>>x>>y;
10. z=x+y;
11. cout<<"\n"<<"Value of z is :"<<z; // displaying the value of z.
12. return 0;
13.}

In the above code, we have declared three variables, i.e., x, y, and z. After
declaration, we take the user input for the values of 'x' and 'y'. Then, we add the
values of 'x' and 'y' and stores their result in 'z' variable.

Output

Enter the values of x and y


8
9
Value of z is :17

Let's see another example of integral expression.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5.
6. int x; // variable declaration
7. int y=9; // variable initialization
8. x=y+int(10.0); // integral expression
9. cout<<"Value of x : "<<x; // displaying the value of x.
10. return 0;
11.}

In the above code, we declare two variables, i.e., x and y. We store the value of
expression (y+int(10.0)) in a 'x' variable.

Output

Value of x : 19

Float Expressions

A float expression is an expression that produces floating-point value as output


after performing all the explicit and implicit conversions.

The following are the examples of float expressions:

1. x+y
2. (x/10) + y
3. 34.5
4. x+float(10)

Let's understand through an example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5.
6. float x=8.9; // variable initialization
7. float y=5.6; // variable initialization
8. float z; // variable declaration
9. z=x+y;
10. std::cout <<"value of z is :" << z<<std::endl; // displaying the value of z.
11.
12.
13. return 0;
14.}

Output

value of z is :14.5

Let's see another example of float expression.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. float x=6.7; // variable initialization
6. float y; // variable declaration
7. y=x+float(10); // float expression
8. std::cout <<"value of y is :" << y<<std::endl; // displaying the value of y
9. return 0;
10.}

In the above code, we have declared two variables, i.e., x and y. After
declaration, we store the value of expression (x+float(10)) in variable 'y'.

Output

value of y is :16.7

Pointer Expressions

A pointer expression is an expression that produces address value as an output.

The following are the examples of pointer expression:

1. &x
2. ptr
3. ptr++
4. ptr-

Let's understand through an example.


1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5.
6. int a[]={1,2,3,4,5}; // array initialization
7. int *ptr; // pointer declaration
8. ptr=a; // assigning base address of array to the pointer ptr
9. ptr=ptr+1; // incrementing the value of pointer
10. std::cout <<"value of second element of an array : " << *ptr<<std::endl;
11. return 0;
12.}

In the above code, we declare the array and a pointer ptr. We assign the base
address to the variable 'ptr'. After assigning the address, we increment the
value of pointer 'ptr'. When pointer is incremented then 'ptr' will be pointing to
the second element of the array.

Output

value of second element of an array : 2

Relational Expressions

A relational expression is an expression that produces a value of type bool,


which can be either true or false. It is also known as a boolean expression.
When arithmetic expressions are used on both sides of the relational operator,
arithmetic expressions are evaluated first, and then their results are compared.

The following are the examples of the relational expression:

1. a>b
2. a-b >= x-y
3. a+b>80

Let's understand through an example

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=45; // variable declaration
6. int b=78; // variable declaration
7. bool y= a>b; // relational expression
8. cout<<"Value of y is :"<<y; // displaying the value of y.
9. return 0;
10.}

In the above code, we have declared two variables, i.e., 'a' and 'b'. After
declaration, we have applied the relational operator between the variables to
check whether 'a' is greater than 'b' or not.

Output

Value of y is :0

Let's see another example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=4; // variable declaration
6. int b=5; // variable declaration
7. int x=3; // variable declaration
8. int y=6; // variable declaration
9. cout<<((a+b)>=(x+y)); // relational expression
10. return 0;
11.}

In the above code, we have declared four variables, i.e., 'a', 'b', 'x' and 'y'. Then,
we apply the relational operator (>=) between these variables.

Output

Logical Expressions

A logical expression is an expression that combines two or more relational


expressions and produces a bool type value. The logical operators are '&&' and
'||' that combines two or more relational expressions.

The following are some examples of logical expressions:

1. a>b && x>y


2. a>10 || b==5

Let's see a simple example of logical expression.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=2;
6. int b=7;
7. int c=4;
8. cout<<((a>b)||(a>c));
9. return 0;
10.}

Output

Bitwise Expressions

A bitwise expression is an expression which is used to manipulate the data at a


bit level. They are basically used to shift the bits.

For example:

x=3

x>>3 // This statement means that we are shifting the three-bit position to the
right.

In the above example, the value of 'x' is 3 and its binary value is 0011. We are
shifting the value of 'x' by three-bit position to the right. Let's understand
through the diagrammatic representation.
Let's see a simple example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x=5; // variable declaration
6. std::cout << (x>>1) << std::endl;
7. return 0;
8. }

In the above code, we have declared a variable 'x'. After declaration, we applied
the bitwise operator, i.e., right shift operator to shift one-bit position to right.

Output

Let's look at another example.


1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x=7; // variable declaration
6. std::cout << (x<<3) << std::endl;
7. return 0;
8. }

In the above code, we have declared a variable 'x'. After declaration, we applied
the left shift operator to variable 'x' to shift the three-bit position to the left.

Output

56

Special Assignment Expressions

Special assignment expressions are the expressions which can be further


classified depending upon the value assigned to the variable.

o Chained Assignment

Chained assignment expression is an expression in which the same value is


assigned to more than one variable by using single statement.

For example:

1. a=b=20
2. or
3. (a=b) = 20

Let's understand through an example.

1. #include <iostream>
2. using namespace std;
3. int main()
4.
5. int a; // variable declaration
6. int b; // variable declaration
7. a=b=80; // chained assignment
8. std::cout <<"Values of 'a' and 'b' are : " <<a<<","<<b<< std::endl;
9. return 0;
10.}

In the above code, we have declared two variables, i.e., 'a' and 'b'. Then, we
have assigned the same value to both the variables using chained assignment
expression.

Output

Values of 'a' and 'b' are : 80,80


Note: Using chained assignment expression, the value cannot be assigned to
the variable at the time of declaration. For example, int a=b=c=90 is an invalid
statement.
o Embedded Assignment Expression

An embedded assignment expression is an assignment expression in which


assignment expression is enclosed within another assignment expression.

Let's understand through an example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a; // variable declaration
6. int b; // variable declaration
7. a=10+(b=90); // embedded assignment expression
8. std::cout <<"Values of 'a' is " <<a<< std::endl;
9. return 0;
10.}

In the above code, we have declared two variables, i.e., 'a' and 'b'. Then, we
applied embedded assignment expression (a=10+(b=90)).

Output

Values of 'a' is 100


o Compound Assignment

A compound assignment expression is an expression which is a combination of


an assignment operator and binary operator.

For example,
1. a+=10;

In the above statement, 'a' is a variable and '+=' is a compound statement.

Let's understand through an example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=10; // variable declaration
6. a+=10; // compound assignment
7. std::cout << "Value of a is :" <<a<< std::endl; // displaying the value of a.
8. return 0;
9. }

In the above code, we have declared a variable 'a' and assigns 10 value to this
variable. Then, we applied compound assignment operator (+=) to 'a' variable,
i.e., a+=10 which is equal to (a=a+10). This statement increments the value of
'a' by 10.

Output

Value of a is :20

Basic Input / Output in C++


C++ comes with libraries that provide us with many ways for performing input
and output. In C++ input and output are performed in the form of a sequence
of bytes or more commonly known as streams.
 Input Stream: If the direction of flow of bytes is from the device(for
example, Keyboard) to the main memory then this process is called input.
 Output Stream: If the direction of flow of bytes is opposite, i.e. from main
memory to device( display screen ) then this process is called output.
Header files available in C++ for Input/Output operations are:
1. iostream: iostream stands for standard input-output stream. This header
file contains definitions of objects like cin, cout, cerr, etc.
2. iomanip: iomanip stands for input-output manipulators. The methods
declared in these files are used for manipulating streams. This file contains
definitions of setw, setprecision, etc.
3. fstream: This header file mainly describes the file stream. This header file is
used to handle the data being read from a file as input or data being
written into the file as output.
4. bits/stdc++: This header file includes every standard library. In
programming contests, using this file is a good idea, when you want to
reduce the time wasted in doing chores; especially when your rank is time
sensitive. To know more about this header file refer this article.
In C++ after the header files, we often use ‘ using namespace std;‘. The reason
behind it is that all of the standard library definitions are inside the
namespace std. As the library functions are not defined at global scope, so in
order to use them we use namespace std. So, that we don’t need to write STD::
at every line (eg. STD::cout etc.). To know more refer this article.
Advertisement
The two instances cout in C++ and cin in C++ of iostream class are used very
often for printing outputs and taking inputs respectively. These two are the
most basic methods of taking input and printing output in C++. To use cin and
cout in C++ one must include the header file iostream in the program.
This article mainly discusses the objects defined in the header file iostream like
the cin and cout.
 Standard output stream (cout): Usually the standard output device is the
display screen. The C++ cout statement is the instance of the ostream class.
It is used to produce output on the standard output device which is usually
the display screen. The data needed to be displayed on the screen is
inserted in the standard output stream (cout) using the insertion
operator(<<).
 C++

#include <iostream>

using namespace std;

int main()

char sample[] = "GeeksforGeeks";

cout << sample << " - A computer science portal for geeks";

return 0;

Output:
GeeksforGeeks - A computer science portal for geeks
Time Complexity: O(1)
Auxiliary Space: O(1)
In the above program, the insertion operator(<<) inserts the value of the string
variable sample followed by the string “A computer science portal for geeks”
in the standard output stream cout which is then displayed on the screen.
 standard input stream (cin): Usually the input device in a computer is the
keyboard. C++ cin statement is the instance of the class istream and is used
to read input from the standard input device which is usually a keyboard.
The extraction operator(>>) is used along with the object cin for reading
inputs. The extraction operator extracts the data from the object cin which
is entered using the keyboard.
 C++

#include <iostream>

using namespace std;

int main()

int age;

cout << "Enter your age:";

cin >> age;

cout << "\nYour age is: " << age;

return 0;

Input :
18
Output:
Enter your age:
Your age is: 18
Time Complexity: O(1)
Auxiliary Space: O(1)
The above program asks the user to input the age. The object cin is connected
to the input device. The age entered by the user is extracted from cin using
the extraction operator(>>) and the extracted data is then stored in the
variable age present on the right side of the extraction operator.
 Un-buffered standard error stream (cerr) : The C++ cerr is the standard error
stream that is used to output the errors. This is also an instance of the
iostream class. As cerr in C++ is un-buffered so it is used when one needs to
display the error message immediately. It does not have any buffer to store
the error message and display it later.
 The main difference between cerr and cout comes when you would like to
redirect output using “cout” that gets redirected to file if you use “cerr” the
error doesn’t get stored in file.(This is what un-buffered means ..It cant
store the message)
 C++

#include <iostream>

using namespace std;

int main()

cerr << "An error occurred";

return 0;

Output:
An error occurred
Time Complexity: O(1)
Auxiliary Space: O(1)
 buffered standard error stream (clog) : This is also an instance of ostream
class and used to display errors but unlike cerr the error is first inserted into
a buffer and is stored in the buffer until it is not fully filled. or the buffer is
not explicitly flushed (using flush()). The error message will be displayed on
the screen too.
 C++

#include <iostream>

using namespace std;

int main()

clog << "An error occurred";


return 0;

Output:
An error occurred
Time Complexity: O(1)
Auxiliary Space: O(1)

C++ if-else

In C++ programming, if statement is used to test the condition. There are


various types of if statements in C++.

o if statement
o if-else statement
o nested if statement
o if-else-if ladder

C++ IF Statement

The C++ if statement tests the condition. It is executed if condition is true.

1. if(condition){
2. //code to be executed
3. }
C++ If Example
1. #include <iostream>
2. using namespace std;
3.
4. int main () {
5. int num = 10;
6. if (num % 2 == 0)
7. {
8. cout<<"It is even number";
9. }
10. return 0;
11.}

Output:/p>

It is even number

C++ IF-else Statement

The C++ if-else statement also tests the condition. It executes if block if
condition is true otherwise else block is executed.

1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is false
5. }

C++ If-else Example


1. #include <iostream>
2. using namespace std;
3. int main () {
4. int num = 11;
5. if (num % 2 == 0)
6. {
7. cout<<"It is even number";
8. }
9. else
10. {
11. cout<<"It is odd number";
12. }
13. return 0;
14.}

Output:

It is odd number
C++ If-else Example: with input from user
1. #include <iostream>
2. using namespace std;
3. int main () {
4. int num;
5. cout<<"Enter a Number: ";
6. cin>>num;
7. if (num % 2 == 0)
8. {
9. cout<<"It is even number"<<endl;
10. }
11. else
12. {
13. cout<<"It is odd number"<<endl;
14. }
15. return 0;
16.}

Output:

Enter a number:11
It is odd number

Output:

Enter a number:12
It is even number

C++ IF-else-if ladder Statement

The C++ if-else-if ladder statement executes one condition from multiple
statements.

1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10.else{
11.//code to be executed if all the conditions are false
12.}

C++ If else-if Example


1. #include <iostream>
2. using namespace std;
3. int main () {
4. int num;
5. cout<<"Enter a number to check grade:";
6. cin>>num;
7. if (num <0 || num >100)
8. {
9. cout<<"wrong number";
10. }
11. else if(num >= 0 && num < 50){
12. cout<<"Fail";
13. }
14. else if (num >= 50 && num < 60)
15. {
16. cout<<"D Grade";
17. }
18. else if (num >= 60 && num < 70)
19. {
20. cout<<"C Grade";
21. }
22. else if (num >= 70 && num < 80)
23. {
24. cout<<"B Grade";
25. }
26. else if (num >= 80 && num < 90)
27. {
28. cout<<"A Grade";
29. }
30. else if (num >= 90 && num <= 100)
31. {
32. cout<<"A+ Grade";
33. }
34. }

Output:

Enter a number to check grade:66


C Grade

Output:

Enter a number to check grade:-2


wrong number

Switch
Switch case statement evaluates a given expression and based on the
evaluated value(matching a certain condition), it executes the statements
associated with it. Basically, it is used to perform different actions based on
different conditions(cases).
 Switch case statements follow a selection-control mechanism and allow a
value to change control of execution.
 They are a substitute for long if statements that compare a variable to
several integral values.
 The switch statement is a multiway branch statement. It provides an easy
way to dispatch execution to different parts of code based on the value of
the expression.
In C++, the switch statement is used for executing one condition from
multiple conditions. It is similar to an if-else-if ladder.
Switch statement consists of conditional based cases and a default case.
In a switch statement, the “case value” can be of “char” and “int” type.
Following are some of the rules while using the switch statement:
1. There can be one or N numbers of cases.
2. The values in the case must be unique.
3. Each statement of the case can have a break statement. It is optional.
Advertisement
Syntax:
switch(expression)
{
case value1: statement_1; break;

case value2: statement_2; break;


.....
......
......
case value_n: statement_n; break;
default: default statement;

 C++

// Q: WA C++ program to returns day based on the numeric value.

#include<iostream>

using namespace std;


class Day

private:

int day;

public:

void set_data()

cout<<"Enter no of day you want to display: ";

cin>>day;

void display_day()

switch (day)

case 1:

cout<<"MONDAY";

break;

case 2:

cout<<"TUESDAY";

break;
case 3:

cout<<"WEDNESDAY";

break;

case 4:

cout<<"THURSDAY";

break;

case 5:

cout<<"FRIDAY";

break;

case 6:

cout<<"SATURDAY";

break;

case 7:

cout<<"SUNDAY";

break;

default:

cout<<"INVALID INPUT";

break;

}
}

};

main()

Day d1;

d1.set_data();

d1.display_day();

return 0;

Output:- Enter no of day you want to display: 1 MONDAY Enter no of day you
want to display: 5 FRIDAY
Some important keywords:
1) Break: This keyword is used to stop the execution inside a switch block. It
helps to terminate the switch block and break out of it.
2) Default: This keyword is used to specify the set of statements to execute if
there is no case match.
Note: Sometimes when default is not placed at the end of switch case
program, we should use break statement with the default case.
Important Points About Switch Case Statements:
1) The expression provided in the switch should result in a constant
value otherwise it would not be valid. Some valid expressions for switch case
will be,
// Constant expressions allowed
switch(1+2+23)
switch(1*2+3%4)
// Variable expression are allowed provided
// they are assigned with fixed values
switch(a*b+c*d)
switch(a+b+c)
2) Duplicate case values are not allowed.
3) The default statement is optional
optional. Even if the switch case statement do not
have a default statement,
it would run without any problem.
4) The break statement is used inside the switch to terminate a
statement sequence. When a break statement is reached, the switch
terminates, and the flow of control jumps to the next line following the switch
statement.
5) The break statement is optional
optional.. If omitted, execution will continue on into
the next case. The flow of control will fall through to subsequent cases until a
break is reached.
6) Nesting of switch stateme
statements is allowed,, which means you can have switch
statements inside another switch. However nested switch statements should
be avoided as it makes the program more complex and less readable.
7) Switch statements are limited to integer values and characters only in the
check condition.
Flowchart:

Example 1:
 C
 C++
// C program to demonstrate syntax of switch

#include <stdio.h>

// Driver Code

int main()

int x = 2;

switch (x) {

case 1:

printf("Choice is 1");

break;

case 2:

printf("Choice is 2");

break;

case 3:

printf("Choice is 3");

break;

default:

printf("Choice other than 1, 2 and 3");

break;

}
return 0;

Output
Choice is 2
C++ For Loop

The C++ for loop is used to iterate a part of the program several times. If the
number of iteration is fixed, it is recommended to use for loop than while or do-
while loops.

The C++ for loop is same as C/C#. We can initialize variable, check condition
and increment/decrement value.

1. for(initialization; condition; incr/decr){


2. //code to be executed
3. }

Flowchart:
C++ For Loop Example
1. #include <iostream>
2. using namespace std;
3. int main() {
4. for(int i=1;i<=10;i++){
5. cout<<i <<"\n";
6. }
7. }

Output:

1
2
3
4
5
6
7
8
9
10

// C++ program to display a pattern


// with 5 rows and 3 columns
#include <iostream>
using namespace std;
int main() {

int rows = 5;
int columns = 3;

for (int i = 1; i <= rows; ++i) {


for (int j = 1; j <= columns; ++j) {
cout << "* ";
}
cout << endl;
}

return 0;
}
Run Code

Output
* * *
* * *
* * *
* * *
* * *

// C++ code to demonstrate star pattern

#include <iostream>

using namespace std;

// Function to demonstrate printing pattern

void pypart(int n)

// Outer loop to handle number of rows

// n in this case

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

// Inner loop to handle number of columns

// values changing acc. to outer loop

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

// Printing stars

cout << "* ";

// Ending line after each row


cout << endl;

// Driver Function

int main()

int n = 5;

pypart(n);

return 0;

Output
*
**
***
****
*****

// C++ code to demonstrate star pattern

#include <iostream>

using namespace std;

// Driver Code

int main()
{

int n = 5;

// looping rows

for (int i = n; i > 0; i--) {

for (int j = 0; j <= n; j++) // looping columns

if (j >= i) {

cout << "*";

else {

cout << " ";

cout << endl;

return 0;

Output
*
**
***
****
*****
// C++ code to demonstrate pattern printing

#include <iostream>

using namespace std;

// Function to demonstrate printing pattern

void pypart2(int n)

int i = 0, j = 0, k = 0;

while (i < n) {

// for number of spaces

while (k < (n - i - 1)) {

cout << " ";

k++;

// resetting k because we want to run k from

// beginning.

k = 0;

while (j <= i) {

cout << "* ";

j++;
}

// resetting k so as it can start from 0.

j = 0;

i++;

cout << endl;

// Driver Code

int main()

int n = 5;

// Function Call

pypart2(n);

return 0;

Output
*
**
***
****
*****
Inverted Pyramid Pattern
 C++

// C++ code to demonstrate star pattern

#include <iostream>

using namespace std;

// Function to demonstrate printing pattern

void pypart(int n)

// Outer loop to handle number of rows

// n in this case

for (int i = n; i > 0; i--) {

// Inner loop to handle number of columns

// values changing acc. to outer loop

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

// Printing stars

cout << "* ";

// Ending line after each row

cout << endl;

}
// Driver Function

int main()

int n = 5;

pypart(n);

return 0;

Output
*****
****
***
**
*
Printing above pattern using while loop
 C++

// C++ code to demonstrate star pattern

#include <iostream>

using namespace std;

// Function to demonstrate printing pattern

void pypart(int n)

// Outer loop to handle number of rows


// n in this case

int i = n, j = 0;

while (i > 0) {

// Inner loop to handle number of columns

// values changing acc. to outer loop

while (j < i) {

// Printing stars

cout << "* ";

j++;

j = 0; // we have to reset j value so as it can

// start from beginning and print * equal to

// i.

i--;

// Ending line after each row

cout << endl;

// Driver Code

int main()
{

int n = 5;

pypart(n);

return 0;

Output
*****
****
***
**
*
Printing Triangle
 Method 1
 Method 2

// C++ code to demonstrate star pattern

#include <iostream>

using namespace std;

// Function to demonstrate printing pattern

void triangle(int n)

// number of spaces

int k = 2 * n - 2;
// Outer loop to handle number of rows

// n in this case

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

// Inner loop to handle number spaces

// values changing acc. to requirement

for (int j = 0; j < k; j++)

cout << " ";

// Decrementing k after each loop

k = k - 1;

// Inner loop to handle number of columns

// values changing acc. to outer loop

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

// Printing stars

cout << "* ";

// Ending line after each row

cout << endl;

}
// Driver Code

int main()

int n = 5;

// Function Call

triangle(n);

return 0;

Output
*
**
***
****
*****

 Method 3

// C++ code to demonstrate star pattern

#include <iostream>

using namespace std;

// Function to demonstrate printing pattern


void pypart2(int n)

int i = 0, j = 0, k = 0;

while (i < n) {

// for spacing

while (k <= n - i - 2) {

cout << " ";

k++;

k = 0;

// For Pattern printing

while (j < 2 * i - 1) {

cout << "*";

j++;

j = 0;

i++;

cout << endl;

}
// Driver Code

int main()

int n = 5;

// Function Call

pypart2(n);

return 0;

Output

*
***
*****
*******
Number Pattern
 CPP

// C++ code to demonstrate printing

// pattern of numbers

#include <iostream>

using namespace std;

// Function to demonstrate printing

// pattern
void numpat(int n)

// initializing starting number

int num = 1;

// Outer loop to handle number of rows

// n in this case

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

// Inner loop to handle number of columns

// values changing acc. to outer loop

for (int j = 0; j <= i; j++)

cout << num << " ";

// Incrementing number at each column

num = num + 1;

// Ending line after each row

cout << endl;

// Driver Code

int main()

{
int n = 5;

// Function Call

numpat(n);

return 0;

Output
1
22
333
4444
55555
Numbers without reassigning
 CPP

// C++ code to demonstrate printing pattern of numbers

#include <iostream>

using namespace std;

// Function to demonstrate printing pattern

void numpat(int n)

// Initialising starting number

int num = 1;

// Outer loop to handle number of rows


// n in this case

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

// Inner loop to handle number of columns

// values changing acc. to outer loop

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

// Printing number

cout << num << " ";

// Incrementing number at each column

num = num + 1;

// Ending line after each row

cout << endl;

// Driver Code

int main()

int n = 5;

// Function Call

numpat(n);
return 0;

Output
1
23
456
7 8 9 10
11 12 13 14 15
Above pattern using while loop
 CPP

// C++ code to demonstrate printing pattern of numbers

#include <iostream>

using namespace std;

// Function to demonstrate printing pattern

void pypart(int n)

int i = 1, j = 0;

// here we declare an num variable which is

// assigned value 1

int num = 1;

while (i <= n) {

while (j <= i - 1) {
// Printing numbers

cout << num << " ";

// here we are increasing num for every

// iteration.

num++;

j++;

j = 0;

i++;

// Ending line after each row

cout << endl;

// Driver Code

int main()

int n = 5;

// Function Call

pypart(n);

return 0;
}

Output
1
23
456
7 8 9 10
11 12 13 14 15

 C++

#include <iostream>

using namespace std;

int main()

int rows = 5, count = 0, count1 = 0, k = 0;

for (int i = 1; i <= rows; ++i) {

for (int space = 1; space <= rows - i; ++space) {

cout << " ";

++count;

while (k != 2 * i - 1) {

if (count <= rows - 1) {

cout << i + k << " ";


++count;

++k;

count1 = count = k = 0;

cout << endl;

return 0;

// code by Kashif RB

Output
1
23
345
4567
56789

 C++

#include <iostream>

using namespace std;

int main()

{
int rows = 5, count = 0, count1 = 0, k = 0;

for (int i = 1; i <= rows; ++i) {

for (int space = 1; space <= rows - i; ++space) {

cout << " ";

++count;

while (k != 2 * i - 1) {

if (count <= rows - 1) {

cout << i + k << " ";

++count;

else {

++count1;

cout << i + k - 2 * count1 << " ";

++k;

count1 = count = k = 0;

cout << endl;

}
return 0;

// code by Kashif Rb

Output
1
232
34543
4567654
567898765
Character Pattern
 CPP

// C++ code to demonstrate printing pattern of alphabets

#include <iostream>

using namespace std;

// Function to demonstrate printing pattern

void alphabet(int n)

// Initializing value corresponding to 'A'

// ASCII value

int num = 65;

// Outer loop to handle number of rows

// n in this case
for (int i = 0; i < n; i++) {

// Inner loop to handle number of columns

// values changing acc. to outer loop

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

// Explicitly converting to char

char ch = char(num);

// Printing char value

cout << ch << " ";

// Incrementing number

num = num + 1;

// Ending line after each row

cout << endl;

// Driver Function

int main()

int n = 5;

alphabet(n);
return 0;

Output
A
BB
CCC
DDDD
EEEEE

Above pattern using while loop


 CPP

// C++ code to demonstrate printing pattern of alphabets

#include <iostream>

using namespace std;

// Function to demonstrate printing pattern

void alphabet(int n)

int i = 1, j = 0;

// assigning ASCII value of A which is 65

int num = 65;

// converting ASCII value to character,

// now our alpha variable is having


// value A after typecasting.

char alpha = char(num);

while (i <= n) {

// alpha is having A value and it

// will change as soon as alpha

// increased or decreased.

while (j <= i - 1) {

cout << alpha << " ";

j++;

// incrementing alpha value so as it can

// point to next character

alpha++;

// we have to reset j value so as it can

// start from beginning and print * equal to

// i.

j = 0;

i++;

// Ending line after each row

cout << endl;


}

// Driver Code

int main()

int n = 5;

// Function Call

alphabet(n);

return 0;

Output
A
BB
CCC
DDDD
EEEEE

Continuous Character pattern


 CPP

// C++ code to demonstrate printing pattern of alphabets

#include <iostream>

using namespace std;


// Function to demonstrate printing pattern

void contalpha(int n)

// Initializing value corresponding to 'A'

// ASCII value

int num = 65;

// Outer loop to handle number of rows

// n in this case

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

// Inner loop to handle number of columns

// values changing acc. to outer loop

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

// Explicitly converting to char

char ch = char(num);

// Printing char value

cout << ch << " ";

// Incrementing number at each column

num = num + 1;

}
// Ending line after each row

cout << endl;

// Driver Code

int main()

int n = 5;

// Function Call

contalpha(n);

return 0;

Output
A
BC
DEF
GHIJ
KLMNO
Above pattern using while loop
 CPP

// C++ code to demonstrate printing pattern of alphabets


#include <iostream>

using namespace std;

// Function to demonstrate printing pattern

void contalpha(int n)

int i = 1, j = 0;

int num = 65;

char alpha = char(num);

while (i <= n) {

while (j <= i - 1) {

cout << alpha << " ";

// incrementing alpha value in every

// iteration so as it can assign to

// next character

alpha++;

j++;

j = 0;

i++;

// Ending line after each row


cout << endl;

// Driver Code

int main()

int n = 5;

// Function Call

contalpha(n);

return 0;

Output
A
BC
DEF
GHIJ
KLMNO
C++ While loop

In C++, while loop is used to iterate a part of the program several times. If the
number of iteration is not fixed, it is recommended to use while loop than for
loop.

1. while(condition){
2. //code to be executed
3. }

Flowchart:
C++ While Loop Example

Let's see a simple example of while loop to print table of 1.

1. #include <iostream>
2. using namespace std;
3. int main() {
4. int i=1;
5. while(i<=10)
6. {
7. cout<<i <<"\n";
8. i++;
9. }
10. }

Output:

1
2
3
4
5
6
7
8
9
10

C++ Do-While Loop

The C++ do-while loop is used to iterate a part of the program several times. If
the number of iteration is not fixed and you must have to execute the loop at
least once, it is recommended to use do-while loop.

The C++ do-while loop is executed at least once because condition is checked
after loop body.

1. do{
2. //code to be executed
3. }while(condition);

Flowchart:

C++ do-while Loop Example

Let's see a simple example of C++ do-while loop to print the table of 1.

1. #include <iostream>
2. using namespace std;
3. int main() {
4. int i = 1;
5. do{
6. cout<<i<<"\n";
7. i++;
8. } while (i <= 10) ;
9. }

Output:

1
2
3
4
5
6
7
8
9
10

C++ Break Statement

The C++ break is used to break loop or switch statement. It breaks the current
flow of the program at the given condition. In case of inner loop, it breaks only
inner loop.

1. jump-statement;
2. break;

Flowchart:
C++ Break Statement Example

Let's see a simple example of C++ break statement which is used inside the
loop.

1. #include <iostream>
2. using namespace std;
3. int main() {
4. for (int i = 1; i <= 10; i++)
5. {
6. if (i == 5)
7. {
8. break;
9. }
10. cout<<i<<"\n";
11. }
12.}

Output:

1
2
3
4

C++ Continue Statement

The C++ continue statement is used to continue loop. It continues the current
flow of the program and skips the remaining code at specified condition. In
case of inner loop, it continues only inner loop.

1. jump-statement;
2. continue;

C++ Continue Statement Example


1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. for(int i=1;i<=10;i++){
6. if(i==5){
7. continue;
8. }
9. cout<<i<<"\n";
10. }
11.}

Output:

1
2
3
4
6
7
8
9
10

C++ Goto Statement


The C++ goto statement is also known as jump statement. It is used to transfer
control to the other part of the program. It unconditionally jumps to the
specified label.

It can be used to transfer control from deeply nested loop or switch case label.

C++ Goto Statement Example


Let's see the simple example of goto statement in C++.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. ineligible:
6. cout<<"You are not eligible to vote!\n";
7. cout<<"Enter your age:\n";
8. int age;
9. cin>>age;
10. if (age < 18){
11. goto ineligible;
12. }
13. else
14. {
15. cout<<"You are eligible to vote!";
16. }
17. }

Output:

You are not eligible to vote!


Enter your age:
16
You are not eligible to vote!
Enter your age:
7
You are not eligible to vote!
Enter your age:
22
You are eligible to vote!

Class: A class in C++ is the building block that leads to Object-Oriented


programming. It is a user-defined data type, which holds its own data
members and member functions, which can be accessed and used by
creating an instance of that class. A C++ class is like a blueprint for an
object. For Example: Consider the Class of Cars. There may be many cars
with different names and brand but all of them will share some common
properties like all of them will have 4 wheels, Speed Limit, Mileage
range etc. So here, Car is the class and wheels, speed limits, mileage are
their properties.
 A Class is a user defined data-type which has data members and
member functions.
 Data members are the data variables and member functions are the
functions used to manipulate these variables and together these data
members and member functions defines the properties and behavior
of the objects in a Class.
 In the above example of class Car, the data member will be speed
limit, mileage etc and member functions can be apply
brakes, increase speed etc.
An Object is an instance of a Class. When a class is defined, no memory
is allocated but when it is instantiated (i.e. an object is created) memory
is allocated.
Defining Class and Declaring Objects
A class is defined in C++ using keyword class followed by the name of
class. The body of class is defined inside the curly brackets and
terminated by a semicolon at the end.
Declaring Objects: When a class is defined, only the specification for
the object is defined; no memory or storage is allocated. To use the data
and access functions defined in the class, you need to create
objects. Syntax:
ClassName ObjectName;
Accessing data members and member functions
functions:: The data members and
member functions of class can be accessed using the dot(‘.’) operator
with the object. For example if the name of object is obj and you want
to access the member function with the namname printName() then you will
have to write obj.printName() .
Accessing Data Members
The public data members are also accessed in the same way given
however the private data members are not allowed to be accessed
directly by the object. Accessing a data memb
memberer depends solely on the
access control of that data member. This access control is given
by Access modifiers in C++
C++. There are three access modifiers : public,
private and protected.
 CPP

// C++ program to demonstrate accessing of data members

#include <bits/stdc++.h>

using namespace std;

class Geeks {
// Access specifier

public:

// Data Members

string geekname;

// Member Functions()

void printname() { cout << "Geekname is:" << geekname; }

};

int main()

// Declare an object of class geeks

Geeks obj1;

// accessing data member

obj1.geekname = "Abhi";

// accessing member function

obj1.printname();

return 0;

Output
Geekname is:Abhi
Member Functions in Classes
There are 2 ways to define a member function:
 Inside class definition
 Outside class definition
To define a member function outside the class definition we have to use
the scope resolution :: operator along with class name and function
name.
 CPP

// C++ program to demonstrate function

// declaration outside class

#include <bits/stdc++.h>

using namespace std;

class Geeks

public:

string geekname;

int id;

// printname is not defined inside class definition

void printname();

// printid is defined inside class definition

void printid()

cout <<"Geek id is: "<<id;

};

// Definition of printname using scope resolution operator ::

void Geeks::printname()

{
cout <<"Geekname is: "<<geekname;

int main() {

Geeks obj1;

obj1.geekname = "xyz";

obj1.id=15;

// call printname()

obj1.printname();

cout << endl;

// call printid()

obj1.printid();

return 0;

Output:
Geekname is: xyz
Geek id is: 15
Note that all the member functions defined inside the class definition
are by default inline, but you can also make any non-class function
inline by using keyword inline with them. Inline functions are actual
functions, which are copied everywhere during compilation, like pre-
processor macro, so the overhead of function calling is reduced. Note:
Declaring a friend function is a way to give private access to a non-
member function.

C++ Object
In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop
etc.
In other words, object is an entity that has state and behavior. Here, state
means data and behavior means functionality.

Object is a runtime entity, it is created at runtime.

Object is an instance of a class. All the members of the class can be accessed
through object.

Let's see an example to create object of student class using s1 as the reference
variable.

1. Student s1; //creating an object of Student

In this example, Student is the type and s1 is the reference variable that refers
to the instance of Student class.

C++ Object and Class Example


Let's see an example of class that has two fields: id and name. It creates
instance of the class, initializes the object and prints the object value.

1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. };
8. int main() {
9. Student s1; //creating an object of Student
10. s1.id = 201;
11. s1.name = "Sonoo Jaiswal";
12. cout<<s1.id<<endl;
13. cout<<s1.name<<endl;
14. return 0;
15. }

Output:

201
Sonoo Jaiswal
Array of Class Objects in C++
An array in C/C++ or be it in any programming language is a collection
of similar data items stored at contiguous memory locations and
elements can be accessed randomly using indices of an array. They can
be used to store the collection of primitive data types such as int, float,
double, char, etc of any particular type. To add to it, an array in C/C++
can store derived data types such as structures, pointers, etc. Given
below is the picture representation of an array.
Example:
Let’s consider an example of taking random integers from the user.

Array

Array of Objects
When a class is defined, only the specification for the object is defined;
no memory or storage is allocated. To use the data and access functions
defined in the class, you need to create objects.
Advertisement

Syntax:
ClassName ObjectName[number of objects];
The Array of Objects stores objects. An array of a class type is also
known as an array of objects.
Example#1:
Storing more than one Employee data. Let’s assume there is an array of
objects for storing employee data emp[50].
Below is the C++ program for storing data of one Employee:

 C++

// C++ program to implement

// the above approach

#include<iostream>

using namespace std;

class Employee

int id;

char name[30];

public:
void getdata();//Declaration of function

void putdata();//Declaration of function

};

void Employee::getdata(){//Defining of function

cout<<"Enter Id : ";

cin>>id;

cout<<"Enter Name : ";

cin>>name;

void Employee::putdata(){//Defining of function

cout<<id<<" ";

cout<<name<<" ";

cout<<endl;

int main(){

Employee emp; //One member

emp.getdata();//Accessing the function

emp.putdata();//Accessing the function

return 0;

Let’s understand the above example –


 In the above example, a class named Employee with id and name is
being considered.
 The two functions are declared-
getdata(): Taking user input for id and name.

 putdata(): Showing the data on the console screen.
This program can take the data of only one Employee. What if there is a
requirement to add data of more than one Employee. Here comes the
answer Array of Objects. An array of objects can be used if there is a
need to store data of more than one employee. Below is the C++
program to implement the above approach-

 C++

// C++ program to implement

// the above approach

#include<iostream>

using namespace std;

class Employee

int id;

char name[30];

public:

// Declaration of function

void getdata();

// Declaration of function

void putdata();

};

// Defining the function outside


// the class

void Employee::getdata()

cout << "Enter Id : ";

cin >> id;

cout << "Enter Name : ";

cin >> name;

// Defining the function outside

// the class

void Employee::putdata()

cout << id << " ";

cout << name << " ";

cout << endl;

// Driver code

int main()

// This is an array of objects having

// maximum limit of 30 Employees

Employee emp[30];
int n, i;

cout << "Enter Number of Employees - ";

cin >> n;

// Accessing the function

for(i = 0; i < n; i++)

emp[i].getdata();

cout << "Employee Data - " << endl;

// Accessing the function

for(i = 0; i < n; i++)

emp[i].putdata();

Output:

Pointer and Class


A pointer to a C++ class is done exactly the same way as a pointer to a structure
and to access members of a pointer to a class you use the member access
operator -> operator, just as you do with pointers to structures. Also as with all
pointers, you must initialize the pointer before using it.
Let us try the following example to understand the concept of pointer to a class

Live Demo
#include <iostream>
using namespace std;
class Box {
public:
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume() {
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
Box *ptrBox; // Declare pointer to a class.

// Save the address of first object


ptrBox = &Box1;
// Now try to access a member using member access operator
cout << "Volume of Box1: " << ptrBox->Volume() << endl;
// Save the address of second object
ptrBox = &Box2;
// Now try to access a member using member access operator
cout << "Volume of Box2: " << ptrBox->Volume() << endl;
return 0;
}
When the above code is compiled and executed, it produces the following
result −
Constructor called.
Constructor called.
Volume of Box1: 5.94
Volume of Box2: 102

Nested Classes in C++


A nested class is a class that is declared in another class. The nested class is also
a member variable of the enclosing class and has the same access rights as the
other members. However, the member functions of the enclosing class have no
special access to the members of a nested class.
A program that demonstrates nested classes in C++ is as follows.

Example
Live Demo

#include<iostream>
using namespace std;
class A {
public:
class B {
private:
int num;
public:
void getdata(int n) {
num = n;
}
void putdata() {
cout<<"The number is "<<num;
}
};
};
int main() {
cout<<"Nested classes in C++"<< endl;
A :: B obj;
obj.getdata(9);
obj.putdata();
return 0;
}

Output
Nested classes in C++
The number is 9
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at
the time of object creation. It is used to initialize the data members of
new objects generally. The constructor in C++ has the same name as the
class or structure. Constructor is invoked at the time of object creation.
It constructs the values i.e. provides data for the object which is why it is
known as constructors.
Constructor does not have a return value, hence they do not have a
return type.
The prototype of Constructors is as follows:
<class-name> (list-of-parameters);
Constructors can be defined inside or outside the class declaration:-
The syntax for defining the constructor within the class:
<class-name> (list-of-parameters) { // constructor definition }
The syntax for defining the constructor outside the class:
<class-name>: :<class-name> (list-of-parameters){ // constructor definition}
Example
 C++

// defining the constructor within the class

#include <iostream>

using namespace std;

class student {

int rno;

char name[10];

double fee;

public:

student()

cout << "Enter the RollNo:";

cin >> rno;

cout << "Enter the Name:";


cin >> name;

cout << "Enter the Fee:";

cin >> fee;

void display()

cout << endl << rno << "\t" << name << "\t" << fee;

};

int main()

student s; // constructor gets called automatically when

// we create the object of the class

s.display();

return 0;

Output
Enter the RollNo:Enter the Name:Enter the Fee:
0 6.95303e-310
A constructor is different from normal functions in following ways:
 Constructor has same name as the class itself
 Default Constructors don’t have input argument however, Copy and
Parameterized Constructors have input arguments
 Constructors don’t have return type
 A constructor is automatically called when an object is created.
 It must be placed in public section of class.
 If we do not specify a constructor, C++ compiler generates a default
constructor for object (expects no parameters and has an empty
body).

Characteristics of the constructor:


 The name of the constructor is the same as its class name.
 Constructors are mostly declared in the public section of the class
though it can be declared in the private section of the class.
 Constructors do not return values; hence they do not have a return
type.
 A constructor gets called automatically when we create the object of
the class.
 Constructors can be overloaded.
 Constructor can not be declared virtual.
 Constructor cannot be inherited.
 Addresses of Constructor cannot be referred.
 Constructor make implicit calls to new and delete operators during
memory allocation.
Types of Constructors
1. Default Constructors: Default constructor is the constructor which
doesn’t take any argument. It has no parameters. It is also called a zero-
argument constructor.

 CPP

// Cpp program to illustrate the

// concept of Constructors

#include <iostream>

using namespace std;


class construct {

public:

int a, b;

// Default Constructor

construct()

a = 10;

b = 20;

};

int main()

// Default constructor called automatically

// when the object is created

construct c;

cout << "a: " << c.a << endl << "b: " << c.b;

return 1;

Output
a: 10
b: 20
Note: Even if we do not define any constructor explicitly, the compiler
will automatically provide a default constructor implicitly.
 C++

// Example

#include<iostream>

using namespace std;

class student

int rno;

char name[50];

double fee;

public:

student() // Explicit Default constructor

cout<<"Enter the RollNo:";

cin>>rno;

cout<<"Enter the Name:";

cin>>name;

cout<<"Enter the Fee:";

cin>>fee;

void display()

{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;

};

int main()

student s;

s.display();

return 0;

2. Parameterized Constructors: It is possible to pass arguments to


constructors. Typically, these arguments help initialize an object when it
is created. To create a parameterized constructor, simply add
parameters to it the way you would to any other function. When you
define the constructor’s body, use the parameters to initialize the
object.
Note: when the parameterized constructor is defined and no default
constructor is defined explicitly, the compiler will not implicitly call the
default constructor and hence creating a simple object as
Student s;
Will flash an error

 CPP

// CPP program to illustrate

// parameterized constructors

#include <iostream>

using namespace std;


class Point {

private:

int x, y;

public:

// Parameterized Constructor

Point(int x1, int y1)

x = x1;

y = y1;

int getX() { return x; }

int getY() { return y; }

};

int main()

// Constructor called

Point p1(10, 15);

// Access values assigned by constructor

cout << "p1.x = " << p1.getX()

<< ", p1.y = " << p1.getY();

return 0;
}

Output
p1.x = 10, p1.y = 15

 C++

// Example

#include<iostream>

#include<string.h>

using namespace std;

class student

int rno;

char name[50];

double fee;

public:

student(int,char[],double);

void display();

};

student::student(int no,char n[],double f)

rno=no;

strcpy(name,n);
fee=f;

void student::display()

cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;

int main()

student s(1001,"Ram",10000);

s.display();

return 0;

When an object is declared in a parameterized constructor, the initial


values have to be passed as arguments to the constructor function. The
normal way of object declaration may not work. The constructors can
be called explicitly or implicitly.
Example e = Example(0, 50); // Explicit call

Example e(0, 50); // Implicit call


 Uses of Parameterized constructor:
1. It is used to initialize the various data elements of different objects
with different values when they are created.
2. It is used to overload constructors.
 Can we have more than one constructor in a class?
Yes, It is called Constructor Overloading.
3. Copy Constructor:
A copy constructor is a member function that initializes an object using
another object of the same class. A detailed article on Copy Constructor.
Whenever we define one or more non-default constructors( with
parameters ) for a class, a default constructor( without parameters )
should also be explicitly defined as the compiler will not provide a
default constructor in this case. However, it is not necessary but it’s
considered to be the best practice to always define a default
constructor.
Copy constructor takes a reference to an object of the same class as an
argument.
Sample(Sample &t)
{
id=t.id;
}

 CPP

// Illustration

#include <iostream>

using namespace std;

class point {

private:

double x, y;

public:

// Non-default Constructor &

// default Constructor

point(double px, double py) { x = px, y = py; }

};

int main(void)

// Define an array of size


// 10 & of type point

// This line will cause error

point a[10];

// Remove above line and program

// will compile without error

point b = point(5, 6);

Output:
Error: point (double px, double py): expects 2 arguments, 0 provided

 C++

// Implicit copy constructor

#include<iostream>

using namespace std;

class Sample

{ int id;

public:

void init(int x)

id=x;

void display()
{

cout<<endl<<"ID="<<id;

};

int main()

Sample obj1;

obj1.init(10);

obj1.display();

Sample obj2(obj1); //or obj2=obj1;

obj2.display();

return 0;

Output
ID=10
ID=10

 C++

// Example: Explicit copy constructor

#include <iostream>

using namespace std;

class Sample
{

int id;

public:

void init(int x)

id=x;

Sample(){} //default constructor with empty body

Sample(Sample &t) //copy constructor

id=t.id;

void display()

cout<<endl<<"ID="<<id;

};

int main()

Sample obj1;

obj1.init(10);
obj1.display();

Sample obj2(obj1); //or obj2=obj1; copy constructor called

obj2.display();

return 0;

Output
ID=10
ID=10

Destructor:
A destructor is also a special member function as a constructor.
Destructor destroys the class objects created by the constructor.
Destructor has the same name as their class name preceded by a tilde
(~) symbol. It is not possible to define more than one destructor. The
destructor is only one way to destroy the object created by the
constructor. Hence destructor can-not be overloaded. Destructor
neither requires any argument nor returns any value. It is automatically
called when the object goes out of scope. Destructors release memory
space occupied by the objects created by the constructor. In destructor,
objects are destroyed in the reverse of object creation.
The syntax for defining the destructor within the class
~ <class-name>()
{
}
The syntax for defining the destructor outside the class
<class-name>: : ~ <class-name>(){}

 C++

#include <iostream>

using namespace std;


class Test {

public:

Test() { cout << "\n Constructor executed"; }

~Test() { cout << "\n Destructor executed"; }

};

main()

Test t;

return 0;

Output
Constructor executed
Destructor executed

 C++

#include <iostream>

using namespace std;

class Test {

public:

Test() { cout << "\n Constructor executed"; }

~Test() { cout << "\n Destructor executed"; }

};

main()
{

Test t, t1, t2, t3;

return 0;

Output
Constructor executed
Constructor executed
Constructor executed
Constructor executed
Destructor executed
Destructor executed
Destructor executed
Destructor executed

 C++

#include <iostream>

using namespace std;

int count = 0;

class Test {

public:

Test()

count++;

cout << "\n No. of Object created:\t" << count;


}

~Test()

cout << "\n No. of Object destroyed:\t" << count;

--count;

};

main()

Test t, t1, t2, t3;

return 0;

Output
No. of Object created: 1
No. of Object created: 2
No. of Object created: 3
No. of Object created: 4
No. of Object destroyed: 4
No. of Object destroyed: 3
No. of Object destroyed: 2
No. of Object destroyed: 1

Characteristics of a destructor:-
1. Destructor is invoked automatically by the compiler when its
corresponding constructor goes out of scope and releases the memory
space that is no longer required by the program.
2. Destructor neither requires any argument nor returns any value
therefore it cannot be overloaded.
3. Destructor cannot be declared as static and const;
4. Destructor should be declared in the public section of the program.
5. Destructor is called in the reverse order of its constructor invocation.

You might also like