Professional Documents
Culture Documents
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.
Program to convert float value into int type using the cast operator
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
#include <iostream>
int main()
double x = 1.2;
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;
// variable
#include <iostream>
int main()
int a;
// this is initialisation of a
a = 10;
// of variable 'a123'
float c;
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++
C++ Expression
1. (a+b) - c
2. (x/y) -z
3. 4a2 - 5b +c
4. (a+b) * (x+y)
Constant expressions
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.
x = (2/3) * 4 (2/3) * 4
extern int y = 67 67
int z = 43 43
static int a = 56 56
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
1. (x * y) -5
2. x + int(9.0)
3. where x and y are the integers.
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
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
1. x+y
2. (x/10) + y
3. 34.5
4. x+float(10)
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
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
1. &x
2. ptr
3. ptr++
4. ptr-
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
Relational Expressions
1. a>b
2. a-b >= x-y
3. a+b>80
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
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
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
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
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
o Chained Assignment
For example:
1. a=b=20
2. or
3. (a=b) = 20
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
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
For example,
1. a+=10;
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
#include <iostream>
int main()
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>
int main()
int 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>
int main()
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>
int main()
Output:
An error occurred
Time Complexity: O(1)
Auxiliary Space: O(1)
C++ if-else
o if statement
o if-else statement
o nested if statement
o if-else-if ladder
C++ IF Statement
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
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. }
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
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.}
Output:
Output:
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;
C++
#include<iostream>
private:
int day;
public:
void set_data()
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:
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.
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
int rows = 5;
int columns = 3;
return 0;
}
Run Code
Output
* * *
* * *
* * *
* * *
* * *
#include <iostream>
void pypart(int n)
// n in this case
// Printing stars
// Driver Function
int main()
int n = 5;
pypart(n);
return 0;
Output
*
**
***
****
*****
#include <iostream>
// Driver Code
int main()
{
int n = 5;
// looping rows
if (j >= i) {
else {
return 0;
Output
*
**
***
****
*****
// C++ code to demonstrate pattern printing
#include <iostream>
void pypart2(int n)
int i = 0, j = 0, k = 0;
while (i < n) {
k++;
// beginning.
k = 0;
while (j <= i) {
j++;
}
j = 0;
i++;
// Driver Code
int main()
int n = 5;
// Function Call
pypart2(n);
return 0;
Output
*
**
***
****
*****
Inverted Pyramid Pattern
C++
#include <iostream>
void pypart(int n)
// n in this case
// Printing stars
}
// Driver Function
int main()
int n = 5;
pypart(n);
return 0;
Output
*****
****
***
**
*
Printing above pattern using while loop
C++
#include <iostream>
void pypart(int n)
int i = n, j = 0;
while (i > 0) {
while (j < i) {
// Printing stars
j++;
// i.
i--;
// Driver Code
int main()
{
int n = 5;
pypart(n);
return 0;
Output
*****
****
***
**
*
Printing Triangle
Method 1
Method 2
#include <iostream>
void triangle(int n)
// number of spaces
int k = 2 * n - 2;
// Outer loop to handle number of rows
// n in this case
k = k - 1;
// Printing stars
}
// Driver Code
int main()
int n = 5;
// Function Call
triangle(n);
return 0;
Output
*
**
***
****
*****
Method 3
#include <iostream>
int i = 0, j = 0, k = 0;
while (i < n) {
// for spacing
while (k <= n - i - 2) {
k++;
k = 0;
while (j < 2 * i - 1) {
j++;
j = 0;
i++;
}
// Driver Code
int main()
int n = 5;
// Function Call
pypart2(n);
return 0;
Output
*
***
*****
*******
Number Pattern
CPP
// pattern of numbers
#include <iostream>
// pattern
void numpat(int n)
int num = 1;
// n in this case
num = num + 1;
// Driver Code
int main()
{
int n = 5;
// Function Call
numpat(n);
return 0;
Output
1
22
333
4444
55555
Numbers without reassigning
CPP
#include <iostream>
void numpat(int n)
int num = 1;
// Printing number
num = num + 1;
// 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
#include <iostream>
void pypart(int n)
int i = 1, j = 0;
// assigned value 1
int num = 1;
while (i <= n) {
while (j <= i - 1) {
// Printing numbers
// iteration.
num++;
j++;
j = 0;
i++;
// 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>
int main()
++count;
while (k != 2 * i - 1) {
++k;
count1 = count = k = 0;
return 0;
// code by Kashif RB
Output
1
23
345
4567
56789
C++
#include <iostream>
int main()
{
int rows = 5, count = 0, count1 = 0, k = 0;
++count;
while (k != 2 * i - 1) {
++count;
else {
++count1;
++k;
count1 = count = k = 0;
}
return 0;
// code by Kashif Rb
Output
1
232
34543
4567654
567898765
Character Pattern
CPP
#include <iostream>
void alphabet(int n)
// ASCII value
// n in this case
for (int i = 0; i < n; i++) {
char ch = char(num);
// Incrementing number
num = num + 1;
// Driver Function
int main()
int n = 5;
alphabet(n);
return 0;
Output
A
BB
CCC
DDDD
EEEEE
#include <iostream>
void alphabet(int n)
int i = 1, j = 0;
while (i <= n) {
// increased or decreased.
while (j <= i - 1) {
j++;
alpha++;
// i.
j = 0;
i++;
// Driver Code
int main()
int n = 5;
// Function Call
alphabet(n);
return 0;
Output
A
BB
CCC
DDDD
EEEEE
#include <iostream>
void contalpha(int n)
// ASCII value
// n in this case
char ch = char(num);
num = num + 1;
}
// Ending line after each row
// 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
void contalpha(int n)
int i = 1, j = 0;
while (i <= n) {
while (j <= i - 1) {
// next character
alpha++;
j++;
j = 0;
i++;
// 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
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
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:
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
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
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;
Output:
1
2
3
4
6
7
8
9
10
It can be used to transfer control from deeply nested loop or switch case label.
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:
#include <bits/stdc++.h>
class Geeks {
// Access specifier
public:
// Data Members
string geekname;
// Member Functions()
};
int main()
Geeks obj1;
obj1.geekname = "Abhi";
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
#include <bits/stdc++.h>
class Geeks
public:
string geekname;
int id;
void printname();
void printid()
};
void Geeks::printname()
{
cout <<"Geekname is: "<<geekname;
int main() {
Geeks obj1;
obj1.geekname = "xyz";
obj1.id=15;
// call printname()
obj1.printname();
// 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 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.
In this example, Student is the type and s1 is the reference variable that refers
to the instance of Student class.
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++
#include<iostream>
class Employee
int id;
char name[30];
public:
void getdata();//Declaration of function
};
cout<<"Enter Id : ";
cin>>id;
cin>>name;
cout<<id<<" ";
cout<<name<<" ";
cout<<endl;
int main(){
return 0;
C++
#include<iostream>
class Employee
int id;
char name[30];
public:
// Declaration of function
void getdata();
// Declaration of function
void putdata();
};
void Employee::getdata()
// the class
void Employee::putdata()
// Driver code
int main()
Employee emp[30];
int n, i;
cin >> n;
emp[i].getdata();
emp[i].putdata();
Output:
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++
#include <iostream>
class student {
int rno;
char name[10];
double fee;
public:
student()
void display()
cout << endl << rno << "\t" << name << "\t" << fee;
};
int main()
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).
CPP
// concept of Constructors
#include <iostream>
public:
int a, b;
// Default Constructor
construct()
a = 10;
b = 20;
};
int main()
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>
class student
int rno;
char name[50];
double fee;
public:
cin>>rno;
cin>>name;
cin>>fee;
void display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
};
int main()
student s;
s.display();
return 0;
CPP
// parameterized constructors
#include <iostream>
private:
int x, y;
public:
// Parameterized Constructor
x = x1;
y = y1;
};
int main()
// Constructor called
return 0;
}
Output
p1.x = 10, p1.y = 15
C++
// Example
#include<iostream>
#include<string.h>
class student
int rno;
char name[50];
double fee;
public:
student(int,char[],double);
void display();
};
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;
CPP
// Illustration
#include <iostream>
class point {
private:
double x, y;
public:
// default Constructor
};
int main(void)
point a[10];
Output:
Error: point (double px, double py): expects 2 arguments, 0 provided
C++
#include<iostream>
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();
obj2.display();
return 0;
Output
ID=10
ID=10
C++
#include <iostream>
class Sample
{
int id;
public:
void init(int x)
id=x;
id=t.id;
void display()
cout<<endl<<"ID="<<id;
};
int main()
Sample obj1;
obj1.init(10);
obj1.display();
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>
public:
};
main()
Test t;
return 0;
Output
Constructor executed
Destructor executed
C++
#include <iostream>
class Test {
public:
};
main()
{
return 0;
Output
Constructor executed
Constructor executed
Constructor executed
Constructor executed
Destructor executed
Destructor executed
Destructor executed
Destructor executed
C++
#include <iostream>
int count = 0;
class Test {
public:
Test()
count++;
~Test()
--count;
};
main()
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.