C++ Tutorial: Constructor
C++ Tutorial: Constructor
C++ tutorial provides basic and advanced concepts of C++. Our C++ tutorial is designed for beginners
and professionals.
Our C++ tutorial includes all topics of C++ such as first example, control statements, objects and
classes, inheritance
, constructor
, destructor, this, static, polymorphism, abstraction, abstract class, interface, namespace, encapsulation, arrays, strings, exception
handling, File IO, etc.
What is C++
C++ is a general purpose, case-sensitive, free-form programming language that supports object-
oriented, procedural and generic programming.C++ is a middle-level language, as it encapsulates both
high and low level language features.
C++ supports the object-oriented programming, the four major pillar of object-oriented programming
(OOPs)
1. Inheritance
2. Polymorphism
3. Encapsulation
4. Abstraction
o The core library includes the data types, variables and literals, etc.
o The standard library includes the set of functions manipulating strings, files, etc.
o The Standard Template Library (STL) includes the set of methods manipulating a data structure.
Usage of C++
By the help of C++ programming language, we can develop different types of secured and robust
applications:
o Window application
o Client-Server application
o Device drivers
o Embedded firmware etc
C++ Program
In this tutorial, all C++ programs are given with C++ compiler so that you can easily change the C++
program code.
File: main.cpp
1. #include <iostream>
2. using namespace std;
3. int main() {
4. cout << "Hello C++ Programming";
5. return 0;
6. }
C vs. C++
What is C?
C is the basic programming language that can be used to develop from the operating systems (like
Windows) to complex programs like Oracle database, Git, Python interpreter, and many more. C
programming language can be called a god's programming language as it forms the base for other
programming languages. If we know the C language, then we can easily learn other programming
languages. C language was developed by the great computer scientist Dennis Ritchie at the Bell
Laboratories. It contains some additional features that make it unique from other programming
languages.
What is C++?
C++ is a special-purpose programming language developed by Bjarne Stroustrup at Bell Labs circa
1980. C++ language is very similar to C language, and it is so compatible with C that it can run 99% of
C programs without changing any source of code though C++ is an object-oriented programming
language, so it is safer and well-structured programming language than C.
7.
No C C++
.
2) Data is less secured in C. In C++, you can use modifiers for class
members to make it inaccessible for outside
users.
5) In C, you can't use functions in In C++, you can use functions in structure.
structure.
7) In C, scanf() and printf() are mainly C++ mainly uses stream cin and cout to
used for input/output. perform input and output operations.
10) C does not provide the feature of C++ supports the feature of namespace.
namespace.
11) Exception handling is not easy in C. It C++ provides exception handling using Try
has to perform using other functions. and Catch block.
C++ Features
C++ Program
Before starting the abcd of C++ language, you need to learn how to write, compile and run the first C+
+ program.
To write the first C++ program, open the C++ console and write the following code:
1. #include <iostream.h>
2. #include<conio.h>
3. void main() {
4. clrscr();
5. cout << "Welcome to C++ Programming.";
6. getch();
7. }
void main() The main() function is the entry point of every program in C++ language. The void
keyword specifies that it returns no value.
cout << "Welcome to C++ Programming." is used to print the data "Welcome to C++
Programming." on the console.
getch() The getch() function asks for a single character. Until you press any key, it blocks the
screen.
C++ I/O operation is using the stream concept. Stream is the sequence of bytes or flow of data. It
makes the performance fast.
If bytes flow from main memory to device like printer, display screen, or a network connection, etc, this
is called as output operation.
If bytes flow from device like printer, display screen, or a network connection, etc to main memory, this
is called as input operation.
Let us see the common header files used in C++ programming are:
<iostream It is used to define the cout, cin and cerr objects, which correspond to standard
> output stream, standard input stream and standard error stream, respectively.
<iomanip It is used to declare services useful for performing formatted I/O, such
> as setprecision and setw.
The cout is a predefined object of ostream class. It is connected with the standard output device,
which is usually a display screen. The cout is used in conjunction with stream insertion operator (<<) to
display the output on a console
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. char ary[] = "Welcome to C++ tutorial";
5. cout << "Value of ary is: " << ary << endl;
6. }
Output:
The cin is a predefined object of istream class. It is connected with the standard input device, which is
usually a keyboard. The cin is used in conjunction with stream extraction operator (>>) to read the
input from a console.
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. int age;
5. cout << "Enter your age: ";
6. cin >> age;
7. cout << "Your age is: " << age << endl;
8. }
Output:
The endl is a predefined object of ostream class. It is used to insert a new line characters and flushes
the stream.
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. cout << "C++ Tutorial";
5. cout << " Javatpoint"<<endl;
6. cout << "End of line"<<endl;
7. }
Output:
C++ Variable
A variable is a name of memory location. It is used to store data. Its value can be changed and it can be
reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
1. int x;
2. float y;
3. char z;
Here, x, y, z are variables and int, float, char are data types.
We can also provide values while declaring the variables as given below:
A variable name can start with alphabet and underscore only. It can't start with digit.
A variable name must not be any reserved word or keyword e.g. char, float etc.
1. int a;
2. int _ab;
3. int a30;
1. int 4;
2. int x y;
3. int double;
A data type specifies the type of data that a variable can store such as integer, floating, character etc.
There are 4 types of data types in C++ language.
The basic data types are integer-based and floating-point based. C++ language supports both signed
and unsigned literals.
The memory size of basic data types may change according to 32 or 64 bit operating system.
Let's see the basic data types. It size is given according to 32 bit OS.
float 4 byte
double 8 byte
C++ Keywords
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. A list of 32
Keywords in C++ Language which are also available in C language are given below.
A list of 30 Keywords in C++ Language which are not available in C language are given
below.
C++ Operators
An operator is simply a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise etc.
There are following types of operators to perform different types of operations in C language.
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operator
o Unary operator
o Misc Operator
The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operators direction to be evaluated, it may be left to right or right to left.
1. int data=5+10*10;
The "data" variable will contain 105 because * (multiplicative operator) is evaluated before + (additive
operator).
C++ Identifiers
C++ identifiers in a program are used to refer to the name of the variables, functions, arrays, or other
user-defined data types created by the programmer. They are the basic requirement of any language.
Every language has its own rules for naming the identifiers.
In short, we can say that the C++ identifiers represent the essential elements in a program which are
given below:
o Constants
o Variables
o Functions
o Labels
Some naming rules are common in both C and C++. They are as follows:
o The identifier name cannot start with a digit, i.e., the first letter should be alphabetical. After the
first letter, we can use letters, digits, or underscores.
o In C++, uppercase and lowercase letters are distinct. Therefore, we can say that C++ identifiers
are case-sensitive.
For example, suppose we have two identifiers, named as 'FirstName', and 'Firstname'. Both the
identifiers will be different as the letter 'N' in the first case in uppercase while lowercase in second.
Therefore, it proves that identifiers are case-sensitive.
Keep Watching
Valid Identifiers
1. Result
2. Test2
3. _sum
4. power
Invalid Identifiers
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a;
6. int A;
7. cout<<"Enter the values of 'a' and 'A'";
8. cin>>a;
9. cin>>A;
10. cout<<"\nThe values that you have entered are : "<<a<<" , "<<A;
11. return 0;
12. }
In the above code, we declare two variables 'a' and 'A'. Both the letters are same but they will behave
as different identifiers. As we know that the identifiers are the case-sensitive so both the identifiers will
have different memory locations.
Keywords are the reserved words that have a special meaning to the compiler. They are reserved for a
special purpose, which cannot be used as the identifiers. For example, 'for', 'break', 'while', 'if', 'else',
etc. are the predefined words where predefined words are those words whose meaning is already
known by the compiler. Whereas, the identifiers are the names which are defined by the programmer
to the program elements such as variables, functions, arrays, objects, classes.
Identifiers Keywords
Identifiers are the names defined by the Keywords are the reserved words whose
programmer to the basic elements of a program. meaning is known by the compiler.
It is used to identify the name of the variable. It is used to specify the type of entity.
It can use both lowercase and uppercase letters. It uses only lowercase letters.
No special character can be used except the It cannot contain any special character.
underscore.
The starting letter of identifiers can be lowercase, It can be started only with the lowercase
uppercase or underscore. letter.
Examples are test, result, sum, power, etc. Examples are 'for', 'if', 'else', 'break', etc.
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.
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
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.
40M
761
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
An integer expression is an expression that produces the integer value as output after performing all
the explicit and implicit conversions.
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.
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.
Float Expressions
A float expression is an expression that produces floating-point value as output after performing all the
explicit and implicit conversions.
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. }
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'.
Pointer Expressions
1. &x
2. ptr
3. ptr++
4. ptr-
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.
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.
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.
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.
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.
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. }
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.
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.
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.
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
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.
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)).
o Compound Assignment
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.
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
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. }
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. }
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. }
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. }
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. }
C++ switch
The C++ switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement in C++.
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break;
5. case value2:
6. //code to be executed;
7. break;
8. ......
9.
10. default:
11. //code to be executed if all cases are not matched;
12. break;
13. }
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. switch (num)
8. {
9. case 10: cout<<"It is 10"; break;
10. case 20: cout<<"It is 20"; break;
11. case 30: cout<<"It is 30"; break;
12. default: cout<<"Not 10, 20 or 30"; break;
13. }
14. }
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:
1. #include <iostream>
2. using namespace std;
3. int main() {
4. for(int i=1;i<=10;i++){
5. cout<<i <<"\n";
6. }
7. }
1. #include <iostream>
2. using namespace std;
3.
4. int main () {
5. for(int i=1;i<=3;i++){
6. for(int j=1;j<=3;j++){
7. cout<<i<<" "<<j<<"\n";
8. }
9. }
10. }
If we use double semicolon in for loop, it will be executed infinite times. Let's see a simple example of
infinite for loop in C++.
1. #include <iostream>
2. using namespace std;
3.
4. int main () {
5. for (; ;)
6. {
7. cout<<"Infinitive For Loop";
8. }
9. }
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. }
In C++, we can use while loop inside another while loop, it is known as nested while loop. The nested
while loop is executed fully when outer loop is executed once.
Let's see a simple example of nested while loop in C++ programming language.
1. #include <iostream>
2. using namespace std;
3. int main () {
4. int i=1;
5. while(i<=3)
6. {
7. int j = 1;
8. while (j <= 3)
9. {
10. cout<<i<<" "<<j<<"\n";
11. j++;
12. }
13. i++;
14. }
15. }
We can also create infinite while loop by passing true as the test condition.
1. #include <iostream>
2. using namespace std;
3. int main () {
4. while(true)
5. {
6. cout<<"Infinitive While Loop";
7. }
8. }
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:
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. }
In C++, if you use do-while loop inside another do-while loop, it is known as nested do-while loop. The
nested do-while loop is executed fully for each outer do-while loop.
1. #include <iostream>
2. using namespace std;
3. int main() {
4. int i = 1;
5. do{
6. int j = 1;
7. do{
8. cout<<i<<"\n";
9. j++;
10. } while (j <= 3) ;
11. i++;
12. } while (i <= 3) ;
13. }
In C++, if you pass true in the do-while loop, it will be infinitive do-while loop.
1. do{
2. //code to be executed
3. }while(true);
1. #include <iostream>
2. using namespace std;
3. int main() {
4. do{
5. cout<<"Infinitive do-while Loop";
6. } while(true);
7. }
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:
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. }
The C++ break statement breaks inner loop only if you use break statement inside the inner loop.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. for(int i=1;i<=3;i++){
6. for(int j=1;j<=3;j++){
7. if(i==2&&j==2){
8. break;
9. }
10. cout<<i<<" "<<j<<"\n";
11. }
12. }
13. }
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.
jump-statement;
1. continue;
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. }
C++ Continue Statement continues inner loop only if you use continue statement inside the inner loop.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. for(int i=1;i<=3;i++){
6. for(int j=1;j<=3;j++){
7. if(i==2&&j==2){
8. continue;
9. }
10. cout<<i<<" "<<j<<"\n";
11. }
12. }
13. }
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.
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. }
C++ Comments
The C++ comments are statements that are not executed by the compiler. The comments in C++
programming can be used to provide explanation of the code, variable, method or class. By the help of
comments, you can hide the program code also.
The single line comment starts with // (double slash). Let's see an example of single line comment in
C++.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x = 11; // x is a variable
6. cout<<x<<"\n";
7. }
asterisk (/∗ ..... ∗/). Let's see an example of multi line comment in C++.
The C++ multi line comment is used to comment multiple lines of code. It is surrounded by slash and
1. #include <ostream>
2. using namespace std;
3. int main()
4. {
5. /* declare and
6. print variable in C++. */
7. int x = 35;
8. cout<<x<<"\n";
9. }
C++ Arrays
Like other programming languages, array in C++ is a group of similar types of elements that have
contiguous memory location.
In C++ std::array is a container that encapsulates fixed size arrays. In C++, array index starts from 0.
We can store only fixed set of elements in C++ array.
o Random Access
o Fixed size
2. Multidimensional Array
Let's see a simple example of C++ array, where we are going to create, initialize and traverse array.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
6. //traversing array
7. for (int i = 0; i < 5; i++)
8. {
9. cout<<arr[i]<<"\n";
10. }
11. }
We can also traverse the array elements using foreach loop. It returns array element one by one.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
6. //traversing array
7. for (int i: arr)
8. {
9. cout<<i<<"\n";
10. }
11. }
C++ Passing Array to Function
In C++, to reuse the array logic, we can create function. To pass array to function in C++, we need to
provide only array name.
Let's see an example of C++ function which prints the array elements.
1. #include <iostream>
2. using namespace std;
3. void printArray(int arr[5]);
4. int main()
5. {
6. int arr1[5] = { 10, 20, 30, 40, 50 };
7. int arr2[5] = { 5, 15, 25, 35, 45 };
8. printArray(arr1); //passing array to function
9. printArray(arr2);
10. }
11. void printArray(int arr[5])
12. {
13. cout << "Printing array elements:"<< endl;
14. for (int i = 0; i < 5; i++)
15. {
16. cout<<arr[i]<<"\n";
17. }
18. }
Let's see an example of C++ array which prints minimum number in an array using function
1. #include <iostream>
2. using namespace std;
3. void printMin(int arr[5]);
4. int main()
5. {
6. int arr1[5] = { 30, 10, 20, 40, 50 };
7. int arr2[5] = { 5, 15, 25, 35, 45 };
8. printMin(arr1);//passing array to function
9. printMin(arr2);
10. }
11. void printMin(int arr[5])
12. {
13. int min = arr[0];
14. for (int i = 0; i > 5; i++)
15. {
16. if (min > arr[i])
17. {
18. min = arr[i];
19. }
20. }
21. cout<< "Minimum element is: "<< min <<"\n";
22. }
Let's see an example of C++ array which prints maximum number in an array using function.
1. #include <iostream>
2. using namespace std;
3. void printMax(int arr[5]);
4. int main()
5. {
6. int arr1[5] = { 25, 10, 54, 15, 40 };
7. int arr2[5] = { 12, 23, 44, 67, 54 };
8. printMax(arr1); //Passing array to function
9. printMax(arr2);
10. }
11. void printMax(int arr[5])
12. {
13. int max = arr[0];
14. for (int i = 0; i < 5; i++)
15. {
16. if (max < arr[i])
17. {
18. max = arr[i];
19. }
20. }
21. cout<< "Maximum element is: "<< max <<"\n";
22. }
C++ Multidimensional Arrays
three dimensional. The data is stored in tabular form (row ∗ column) which is also known as matrix.
The multidimensional array is also known as rectangular arrays in C++. It can be two dimensional or
Let's see a simple example of multidimensional array in C++ which declares, initializes and traverse
two dimensional arrays.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int test[3][3]; //declaration of 2D array
6. test[0][0]=5; //initialization
7. test[0][1]=10;
8. test[1][1]=15;
9. test[1][2]=20;
10. test[2][0]=30;
11. test[2][2]=10;
12. //traversal
13. for(int i = 0; i < 3; ++i)
14. {
15. for(int j = 0; j < 3; ++j)
16. {
17. cout<< test[i][j]<<" ";
18. }
19. cout<<"\n"; //new line at each row
20. }
21. return 0;
22. }
Let's see a simple example of multidimensional array which initializes array at the time of declaration.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int test[3][3] =
6. {
7. {2, 5, 5},
8. {4, 0, 3},
9. {9, 1, 8} }; //declaration and initialization
10. //traversal
11. for(int i = 0; i < 3; ++i)
12. {
13. for(int j = 0; j < 3; ++j)
14. {
15. cout<< test[i][j]<<" ";
16. }
17. cout<<"\n"; //new line at each row
18. }
19. return 0;
20. }
C++ Pointers
The pointer in C++ language is a variable, it is also known as locator or indicator that points to an
address of a value.
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc.
and used with arrays, structures and functions.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer
is used.
Pointers in c language are widely used in arrays, functions and structures. It reduces the code and
improves the performance.
Symbols used in pointer
Declaring a pointer
Pointer Example
Let's see the simple example of using pointers printing the address and value.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int number=30;
6. int ∗ p;
7. p=&number;//stores the address of number variable
8. cout<<"Address of number variable is:"<<&number<<endl;
9. cout<<"Address of p variable is:"<<p<<endl;
10. cout<<"Value of p variable is:"<<*p<<endl;
11. return 0;
12. }
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=20,b=10,∗p1=&a,∗p2=&b;
6. cout<<"Before swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
7. ∗p1=∗p1+∗p2;
8. ∗p2=∗p1-∗p2;
9. ∗p1=∗p1-∗p2;
10. cout<<"After swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
11. return 0;
12. }
sizeof() operator in C++
The sizeof() is an operator that evaluates the size of data type, constants, variable. It is a compile-time
operator as it returns the size of any variable or a constant at the compilation time.
The size, which is calculated by the sizeof() operator, is the amount of RAM occupied in the computer.
1. sizeof(data_type);
In the above syntax, the data_type can be the data type of the data, variables, constants, unions,
structures, or any other user-defined data type.
Keep Watching
If the parameter of a sizeof() operator contains the data type of a variable, then the sizeof() operator
will return the size of the data type.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. // Determining the space in bytes occupied by each data type.
6. std::cout << "Size of integer data type : " <<sizeof(int)<< std::endl;
7. std::cout << "Size of float data type : " <<sizeof(float)<< std::endl;
8. std::cout << "Size of double data type : " <<sizeof(double)<< std::endl;
9. std::cout << "Size of char data type : " <<sizeof(char)<< std::endl;
10. return 0;
11. }
In the above program, we have evaluated the size of the in-built data types by using the sizeof()
operator. As we know that int occupies 4 bytes, float occupies 4 bytes, double occupies 8 bytes, and
char occupies 1 byte, and the same result is shown by the sizeof() operator as we can observe in the
following output.
1. #include <iostream>
2. using namespace std;
3. class Base
4. {
5. int a;
6. };
7. int main()
8. {
9. Base b;
10. std::cout << "Size of class base is : "<<sizeof(b) << std::endl;
11. return 0;
12. }
Array of Pointers
An array of pointers is an array that consists of variables of pointer type, which means that the variable
is a pointer addressing to some other element. Suppose we create an array of pointer holding 5 integer
pointers; then its declaration would look like:
In the above declaration, we declare an array of pointer named as ptr, and it allocates 5 integer
pointers in memory.
The element of an array of a pointer can also be initialized by assigning the address of some other
element. Let's observe this case through an example.
In the above code, we are assigning the address of 'a' variable to the third element of an array 'ptr'.
1. *ptr[2];
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int ptr1[5]; // integer array declaration
6. int *ptr2[5]; // integer array of pointer declaration
7. std::cout << "Enter five numbers :" << std::endl;
8. for(int i=0;i<5;i++)
9. {
10. std::cin >> ptr1[i];
11. }
12. for(int i=0;i<5;i++)
13. {
14. ptr2[i]=&ptr1[i];
15. }
16. // printing the values of ptr1 array
17. std::cout << "The values are" << std::endl;
18. for(int i=0;i<5;i++)
19. {
20. std::cout << *ptr2[i] << std::endl;
21. }
22. }
Array of Pointer to Strings
An array of pointer to strings is an array of character pointers that holds the address of the first
character of a string or we can say the base address of a string.
The following are the differences between an array of pointers to string and two-dimensional array of
characters:
o An array of pointers to string is more efficient than the two-dimensional array of characters in
case of memory consumption because an array of pointer to strings consumes less memory
than the two-dimensional array of characters to store the strings.
o In an array of pointers, the manipulation of strings is comparatively easier than in the case of 2d
array. We can also easily change the position of the strings by using the pointers.
In the above code, we declared an array of pointer names as 'names' of size 5. In the above case, we
have done the initialization at the time of declaration, so we do not need to mention the size of the
array of a pointer. The above code can be re-written as:
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. char *names[5] = {"john",
6. "Peter",
7. "Marco",
8. "Devin",
9. "Ronan"};
10. for(int i=0;i<5;i++)
11. {
12. std::cout << names[i] << std::endl;
13. }
14. return 0;
15. }
In the above code, we have declared an array of char pointer holding 5 string literals, and the first
character of each string is holding the base address of the string.
A void pointer is a general-purpose pointer that can hold the address of any data type, but it is not
associated with any data type.
In C++, we cannot assign the address of a variable to the variable of a different data type. Consider the
following example:
In the above example, we declare a pointer of type integer, i.e., ptr and a float variable, i.e., 'a'. After
declaration, we try to store the address of 'a' variable in 'ptr', but this is not possible in C++ as the
variable cannot hold the address of different data types.
1. #include <iostream.h>
2. using namespace std;
3. int main()
4. {
5. int *ptr;
6. float f=10.3;
7. ptr = &f; // error
8. std::cout << "The value of *ptr is : " <<*ptr<< std::endl;
9. return 0;
10. }
In C, we can assign the void pointer to any other pointer type without any typecasting, whereas in C+
+, we need to typecast when we assign the void pointer type to any other pointer type.
In C,
1. #include <stdio.h>
2. int main()
3. {
4. void *ptr; // void pointer declaration
5. int *ptr1; // integer pointer declaration
6. int a =90; // integer variable initialization
7. ptr=&a; // storing the address of 'a' in ptr
8. ptr1=ptr; // assigning void pointer to integer pointer type.
9. printf("The value of *ptr1 : %d",*ptr1);
10. return 0;
11. }
In C++,
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. void *ptr; // void pointer declaration
6. int *ptr1; // integer pointer declaration
7. int data=10; // integer variable initialization
8. ptr=&data; // storing the address of data variable in void pointer variable
9. ptr1=(int *)ptr; // assigning void pointer to integer pointer
10. std::cout << "The value of *ptr1 is : " <<*ptr1<< std::endl;
11. return 0;
12. }
C++ References
Till now, we have read that C++ supports two types of variables:
o An ordinary variable is a variable that contains the value of some type. For example, we create a
variable of type int, which means that the variable can hold the value of type integer.
o A pointer is a variable that stores the address of another variable. It can be dereferenced to
retrieve the value to which this pointer points to.
o There is another variable that C++ supports, i.e., references. It is a variable that behaves as an
alias for another variable.
Reference can be created by simply using an ampersand (&) operator. When we create a variable, then
it occupies some memory location. We can create a reference of the variable; therefore, we can access
the original variable by using either name of the variable or reference. For example,
1. int a=10;
1. int &ref=a;
The above statement means that 'ref' is a reference variable of 'a', i.e., we can use the 'ref' variable in
place of 'a' variable.ion Handling in Java - Javatpoint
o References as aliases
It can be declared by using & operator with the reference type variable.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=10;
6. int &value=a;
7. std::cout << value << std::endl;
8. return 0;
9. }
References as aliases
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=70; // variable initialization
6. int &b=a;
7. int &c=a;
8. std::cout << "Value of a is :" <<a<< std::endl;
9. std::cout << "Value of b is :" <<b<< std::endl;
10. std::cout << "Value of c is :" <<c<< std::endl;
11. return 0;}
In the above code, we create a variable 'a' which contains a value '70'. We have declared two reference
variables, i.e., b and c, and both are referring to the same variable 'a'. Therefore, we can say that 'a'
variable can be accessed by 'b' and 'c' variable.
Properties of References
Initializátion
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=10; // variable initialization
6. int &b=a; // b reference to a
7. std::cout << "value of a is " <<b<< std::endl;
8. return 0;
9. }
In the above code, we have created a reference variable, i.e., 'b'. At the time of declaration,
'a' variable is assigned to 'b'. If we do not assign at the time of declaration, then the code
would look like:
1. int &b;
2. &b=a;
The above code will throw a compile-time error as 'a' is not assigned at the time of declaration.
Output
Reassignment
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x=11; // variable initialization
6. int z=67;
7. int &y=x; // y reference to x
8. int &y=z; // y reference to z, but throws a compile-time error.
9. return 0;}
In the above code, 'y' reference variable is referring to 'x' variable, and then 'z' is assigned to 'y'. But
this reassignment is not possible with the reference variable, so it throws a compile-time error.
Compile-time error
Function Parameters
References can also be passed as a function parameter. It does not create a copy of the argument and
behaves as an alias for a parameter. It enhances the performance as it does not create a copy of the
argument.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=9; // variable initialization
6. int b=10; // variable initialization
7. swap(a, b); // function calling
8. std::cout << "value of a is :" <<a<< std::endl;
9. std::cout << "value of b is :" <<b<< std::endl;
10. return 0;
11. }
12. void swap(int &p, int &q) // function definition
13. {
14. int temp; // variable declaration
15. temp=p;
16. p=q;
17. q=temp;
18. }
In the above code, we are swapping the values of 'a' and 'b'. We have passed the variables 'a' and 'b' to
the swap() function. In swap() function, 'p' is referring to 'a' and 'q' is referring to 'b'. When we swap the
values of 'p' and 'q' means that the values of 'a' and 'b' are also swapped.
References as shortcuts
With the help of references, we can easily access the nested data.
1. #include <iostream>
2. using namespace std;
3. struct profile
4. {
5. int id;
6. };
7. struct employee
8. {
9. profile p;
10. };
11. int main()
12. {
13. employee e;
14. int &ref=e.p.id;
15. ref=34;
16. std::cout << e.p.id << std::endl;
17. }
In the above code, we are trying to access the 'id' of the profile struct of the employee. We generally
access this member by using the statement e.p.id, but this would be a tedious task if we have multiple
access to this member. To avoid this situation, we create a reference variable, i.e., ref, which is another
name of 'e.p.id'.
C++ reference and pointer seem to be similar, but there are some differences that exist between them.
A reference is a variable which is another name of the existing variable, while the pointer is variable
that stores the address of another variable.
What is Reference?
A reference is a variable
that is referred to as another name for an already existing variable. The reference of a variable is created by storing the address
of another variable.
A reference variable can be considered as a constant pointer with automatic indirection. Here,
automatic indirection means that the compiler automatically applies the indirection operator (*).
Example of reference:
Keep Watching
1. int &a = i;
In the above declaration, 'a' is an alias name for 'i' variable. We can also refer to the 'i' variable through
'a' variable also.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int i=8; // variable initialization
6. int &a=i; // creating a reference variable
7. cout<<"The value of 'i' variable is :"<<a;
8. return 0;
9. }
In the above code, we have created a reference variable, i.e., 'a' for 'i' variable. After creating a
reference variable, we can access the value of 'i' with the help of 'a' variable.
What is Pointer?
A pointer is a variable that contains the address of another variable. It can be dereferenced with the
help of (*) operator
o Definition
A reference variable is another name for an already existing variable. It is mainly used in 'pass by
reference' where the reference variable is passed as a parameter to the function and the function to
which this variable is passed works on the original copy of the variable.
Let's understand through a simple example.
1. #include <iostream>
2. using namespace std;
3. void func(int &);
4. int main()
5. {
6. int a=10;
7. std::cout <<"Value of 'a' is :" <<a<< std::endl;
8. func(a);
9. std::cout << "Now value of 'a' is :" <<a<< std::endl;
10. return 0;
11. }
12. void func(int &m)
13. {
14. m=8;
15. }
Whereas, Pointer
is a variable that stores the address of another variable. It makes the programming easier as it holds the memory address of
some variable.
o Declaration
We can declare a reference variable by adding a '&' symbol before a variable. If this symbol is used in
the expression, then it will be treated as an address operator.
Before using a pointer variable, we should declare a pointer variable, and this variable is created by
adding a '*' operator before a variable.
o Reassignment
We cannot reassign the reference variable. Now, we take a simple example as given below:
1. #include <iostream>
2. using namespace std;
3. void func(int &);
4. int main()
5. {
6. int i; // variable declaration
7. int k; // variable declaration
8. int &a=i;
9. int &a=k; // error
10. return 0;
11. }
The above code shows the error that multiple declarations of int &a are not allowed. Therefore, the
above program concludes that reassignment operation is not valid for the reference variable.
Whereas, the pointers can be re-assigned. This reassignment is useful when we are working with the
data structures such as linked list, trees, etc.
o Memory Address
In the case of reference, both the reference and actual variable refer to the same address. The new
variable will not be assigned to the reference variable until the actual variable is either deleted or goes
out of the scope.
1. #include <iostream>
2. using namespace std;
3. void func(int &);
4. int main()
5. {
6. int i;
7. int &a=i;
8. std::cout << "The address of 'a' variable is : " <<&a<< std::endl;
9. std::cout << "The address of 'i' variable is : " <<&i<< std::endl;
10. return 0;
11. }
The above output shows that both the reference variable and the actual variable have the same
address.
In the case of pointers, both the pointer variable and the actual variable will have different memory
addresses. Let's understand this through an example.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int k;
6. int *p;
7. p=&k;
8. cout<<"The memory address of p variable is :"<<&p;
9. cout<<"\nThe memory address of k variable is :"<<&k;
10. return 0;
11. }
o NULL value
We cannot assign the NULL value to the reference variable, but the pointer variable can be assigned
with a NULL value.
o Indirection
Pointers can have pointer to pointer offering more than one level of indirection.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int *p;
6. int a=8;
7. int **q;
8. p=&a;
9. q=&p;
10. std::cout << "The value of q is : " <<*q<< std::endl;
11. return 0;
12. }
In the above code, the pointer 'p' is pointing to variable 'a' while 'q' is a double pointer which is pointing
to 'p'. Therefore, we can say that the value of 'p' would be the address of 'a' variable and the value of
'q' variable would be the address of 'p' variable.
In the case of References, reference to reference is not possible. If we try to do c++ program
o Arithmetic Operations
As we know that arithmetic operations can be applied to the pointers named as "Pointer Arithmetic",
but arithmetic operations cannot be applied on the references. There is no word, i.e., Reference
Arithmetic exists in C++
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a[]={1,2,3,4,5}; // array initialization
6. int *ptr; // pointer declaration
7. ptr=a; assigning base address to pointer ptr.
8. cout<<"The value of *ptr is :"<<*ptr;
9. ptr=ptr+1; // incrementing the value of ptr by 1.
10. std::cout << "\nThe value of *ptr is: " <<*ptr<< std::endl;
11. return 0;
12. }
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5.
6. int value=90; // variable declaration
7. int &a=value; // assigning value to the reference
8. &a=&a+5 // arithmetic operation is not possible with reference variable, it throws an error.
9. return 0;
10. }
The above code will throw a compile-time error as arithmetic operations are not allowed with
references.
As we know that pointers are used to point some variables; similarly, the function pointer is a pointer
used to point functions. It is basically used to store the address of a function. We can call the function
by using the function pointer, or we can also pass the pointer to another function as a parameter.
They are mainly useful for event-driven applications, callbacks, and even for storing the functions in
arrays.
Computer only understands the low-level language, i.e., binary form. The program we write in C++ is
always in high-level language, so to convert the program into binary form, we use compiler. Compiler is
a program that converts source code into an executable file. This executable file gets stored in RAM.
The CPU starts the execution from the main() method, and it reads the copy in RAM but not the original
file.
All the functions and machine code instructions are data. This data is a bunch of bytes, and all these
bytes have some address in RAM. The function pointer contains RAM address of the first instruction of a
function.
The above syntax is the function declaration. As functions are not simple as variables, but C++ is a
type safe, so function pointers have return type and parameter list. In the above syntax, we first supply
the return type, and then the name of the pointer, i.e., FuncPtr which is surrounded by the brackets and
preceded by the pointer symbol, i.e., (*). After this, we have supplied the parameter list (int,int). The
above function pointer can point to any function which takes two integer parameters and returns
integer type value.
Address of a function
We can get the address of a function very easily. We just need to mention the name of the function, we
do not need to call the function.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. std::cout << "Address of a main() function is : " <<&main<< std::endl;
6. return 0;
7. }
In the above program, we are displaying the address of a main() function. To print the address of a
main() function, we have just mentioned the name of the function, there is no bracket not parameters.
Therefore, the name of the function by itself without any brackets or parameters means the address of
a function.
We can use the alternate way to print the address of a function, i.e., &main.
We can call the function with the help of a function pointer by simply using the name of the function
pointer. The syntax of calling the function through the function pointer would be similar as we do the
calling of the function normally.
1. #include <iostream>
2. using namespace std;
3. int add(int a , int b)
4. {
5. return a+b;
6. }
7. int main()
8. {
9. int (*funcptr)(int,int); // function pointer declaration
10. funcptr=add; // funcptr is pointing to the add function
11. int sum=funcptr(5,5);
12. std::cout << "value of sum is :" <<sum<< std::endl;
13. return 0;
14. }
In the above program, we declare the function pointer, i.e., int (*funcptr)(int,int) and then we store the
address of add() function in funcptr. This implies that funcptr contains the address of add() function.
Now, we can call the add() function by using funcptr. The statement funcptr(5,5) calls the add()
function, and the result of add() function gets stored in sum variable.
Output:
1. #include <iostream>
2. using namespace std;
3. void printname(char *name)
4. {
5. std::cout << "Name is :" <<name<< std::endl;
6. }
7.
8. int main()
9. {
10. char s[20]; // array declaration
11. void (*ptr)(char*); // function pointer declaration
12. ptr=printname; // storing the address of printname in ptr.
13. std::cout << "Enter the name of the person: " << std::endl;
14. cin>>s;
15. cout<<s;
16. ptr(s); // calling printname() function
17. return 0;
18. }
Passing a function pointer as a parameter
1. #include <iostream>
2. using namespace std;
3. void func1()
4. {
5. cout<<"func1 is called";
6. }
7. void func2(void (*funcptr)())
8. {
9. funcptr();
10. }
11. int main()
12. {
13. func2(func1);
14. return 0;
15. }
In the above code, the func2() function takes the function pointer as a parameter. The main() method
calls the func2() function in which the address of func1() is passed. In this way, the func2() function is
calling the func1() indirectly.
As we know that arrays store the homogeneous data, so most of the time, memory is allocated to the
array at the declaration time. Sometimes the situation arises when the exact memory is not
determined until runtime. To avoid such a situation, we declare an array with a maximum size, but
some memory will be unused. To avoid the wastage of memory, we use the new operator to allocate
the memory dynamically at the run time.
In C language, we use the malloc() or calloc() functions to allocate the memory dynamically at run
time, and free() function is used to deallocate the dynamically allocated memory. C++ also supports
these functions, but C++ also defines unary operators such as new and delete to perform the same
tasks, i.e., allocating and freeing the memory.
New operator
A new operator is used to create the object while a delete operator is used to delete the object. When
the object is created by using the new operator, then the object will exist until we explicitly use the
delete operator to delete the object. Therefore, we can say that the lifetime of the object is not related
to the block structure of the program.
Syntax
The above syntax is used to create the object using the new operator. In the above
syntax, 'pointer_variable' is the name of the pointer variable, 'new' is the operator, and 'data-
type' defines the type of the data.
Example 1:
1. int *p;
2. p = new int;
Example 2:
1. float *q;
2. q = new float;
In the above case, the declaration of pointers and their assignments are done separately. We can also
combine these two statements as follows:
1. int *p = new int;
2. float *q = new float;
Assigning a value to the newly created object
o We can assign the value to the newly created object by simply using the assignment operator.
In the above case, we have created two pointers 'p' and 'q' of type int and float, respectively.
Now, we assign the values as follows:
1. *p = 45;
2. *q = 9.8;
We assign 45 to the newly created int object and 9.8 to the newly created float object.
o We can also assign the values by using new operator which can be done as follows:
As we know that new operator is used to create memory space for any data-type or even user-defined
data type such as an array, structures, unions, etc., so the syntax for creating a one-dimensional array
is given below:
In the above statement, we have created an array of type int having a size equal to 8 where p[0] refers
first element, p[1] refers the first element, and so on.
Delete operator
When memory is no longer required, then it needs to be deallocated so that the memory can be used
for another purpose. This can be achieved by using the delete operator, as shown below:
1. delete pointer_variable;
In the above statement, 'delete' is the operator used to delete the existing object,
and 'pointer_variable' is the name of the pointer variable.
In the previous case, we have created two pointers 'p' and 'q' by using the new operator, and can be
deleted by using the following statements:
1. delete p;
2. delete q;
The dynamically allocated array can also be removed from the memory space by using the following
syntax:
In the above statement, we need to specify the size that defines the number of elements that are
required to be freed. The drawback of this syntax is that we need to remember the size of the array.
But, in recent versions of C++, we do not need to mention the size as follows:
1. delete [ ] pointer_variable;
1. #include <iostream>
2. using namespace std
3. int main()
4. {
5. int size; // variable declaration
6. int *arr = new int[size]; // creating an array
7. cout<<"Enter the size of the array : ";
8. std::cin >> size; //
9. cout<<"\nEnter the element : ";
10. for(int i=0;i<size;i++) // for loop
11. {
12. cin>>arr[i];
13. }
14. cout<<"\nThe elements that you have entered are :";
15. for(int i=0;i<size;i++) // for loop
16. {
17. cout<<arr[i]<<",";
18. }
19. delete arr; // deleting an existing array.
20. return 0;
21. }
In the above code, we have created an array using the new operator. The above program will take the
user input for the size of an array at the run time. When the program completes all the operations, then
it deletes the object by using the statement delete arr.
The following are the advantages of the new operator over malloc() function:
o It does not use the sizeof() operator as it automatically computes the size of the data object.
o It automatically returns the correct data type pointer, so it does not need to use the typecasting.
o Like other operators, the new and delete operator can also be overloaded.
o It also allows you to initialize the data object while creating the memory space for the object
malloc() vs new in C++
Both the malloc() and new in C++ are used for the same purpose. They are used for allocating
memory at the runtime. But, malloc() and new have different syntax. The main difference between the
malloc() and new is that the new is an operator while malloc() is a standard library function that is
predefined in a stdlib header file.
What is new?
The new is a memory allocation operator, which is used to allocate the memory at the runtime. The
memory initialized by the new operator is allocated in a heap. It returns the starting address of the
memory, which gets assigned to the variable. The functionality of the new operator in C++ is similar to
the malloc() function, which was used in the C programming language. C++ is compatible with the
malloc() function also, but the new operator is mostly used because of its advantages.
type: It defines the datatype of the variable for which the memory is allocated by the new operator.
The new operator does not use the sizeof() operator to allocate the memory. It also does not use the
resize as the new operator allocates sufficient memory for an object. It is a construct that calls the
constructor at the time of declaration to initialize an object.
As we know that the new operator allocates the memory in a heap; if the memory is not available in a
heap and the new operator tries to allocate the memory, then the exception is thrown. If our code is
not able to handle the exception, then the program will be terminated abnormally.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int *ptr; // integer pointer variable declaration
6. ptr=new int; // allocating memory to the pointer variable ptr.
7. std::cout << "Enter the number : " << std::endl;
8. std::cin >>*ptr;
9. std::cout << "Entered number is " <<*ptr<< std::endl;
10. return 0;
11. }
What is malloc()?
A malloc() is a function that allocates memory at the runtime. This function returns the void pointer,
which means that it can be assigned to any pointer type. This void pointer can be further typecast to
get the pointer that points to the memory of a specified type.
where,
type: it is the datatype of the variable for which the memory has to be allocated.
variable_name: It defines the name of the variable that points to the memory.
(type*): It is used for typecasting so that we can get the pointer of a specified type that points to the
memory.
sizeof(): The sizeof() operator is used in the malloc() function to obtain the memory size required for
the allocation.
1. #include <iostream>
2. #include<stdlib.h>
3. using namespace std;
4.
5. int main()
6. {
7.
8. int len; // variable declaration
9. std::cout << "Enter the count of numbers :" << std::endl;
10. std::cin >> len;
11. int *ptr; // pointer variable declaration
12. ptr=(int*) malloc(sizeof(int)*len); // allocating memory to the poiner variable
13. for(int i=0;i<len;i++)
14. {
15. std::cout << "Enter a number : " << std::endl;
16. std::cin >> *(ptr+i);
17. }
18. std::cout << "Entered elements are : " << std::endl;
19. for(int i=0;i<len;i++)
20. {
21. std::cout << *(ptr+i) << std::endl;
22. }
23. free(ptr);
24. return 0;
25. }
Output:
If we do not use the free() function at the correct place, then it can lead to the cause of the dangling
pointer. Let's understand this scenario through an example.
1. #include <iostream>
2. #include<stdlib.h>
3. using namespace std;
4. int *func()
5. {
6. int *p;
7. p=(int*) malloc(sizeof(int));
8. free(p);
9. return p;
10. }
11. int main()
12. {
13.
14. int *ptr;
15. ptr=func();
16. free(ptr);
17. return 0;
18. }
In the above code, we are calling the func() function. The func() function returns the integer pointer.
Inside the func() function, we have declared a *p pointer, and the memory is allocated to this pointer
variable using malloc() function. In this case, we are returning the pointer whose memory is already
released. The ptr is a dangling pointer as it is pointing to the released memory location. Or we can say
ptr is referring to that memory which is not pointed by the pointer.
Till now, we get to know about the new operator and the malloc() function. Now, we will see the
differences between the new operator and the malloc() function.
Differences between the malloc() and new
o The new operator constructs an object, i.e., it calls the constructor to initialize an object
while malloc() function does not call the constructor. The new operator invokes the constructor,
and the delete operator invokes the destructor to destroy the object. This is the biggest
difference between the malloc() and new.
o The new is an operator, while malloc() is a predefined function in the stdlib header file.
o The operator new can be overloaded while the malloc() function cannot be overloaded.
o If the sufficient memory is not available in a heap, then the new operator will throw an exception
while the malloc() function returns a NULL pointer.
o In the new operator, we need to specify the number of objects to be allocated while in malloc()
function, we need to specify the number of bytes to be allocated.
o In the case of a new operator, we have to use the delete operator to deallocate the memory. But
in the case of malloc() function, we have to use the free() function to deallocate the memory.
where,
For example,
1. int *p;
2. p = new int;
In the above statements, we are declaring an integer pointer variable. The statement p = new
int; allocates the memory space for an integer variable.
For example,
1. int *p;
2. p = (int *) malloc(sizeof(int))
The above statement will allocate the memory for an integer variable in a heap, and then stores the
address of the reserved memory in 'p' variable.
o On the other hand, the memory allocated using malloc() function can be deallocated using the
free() function.
o Once the memory is allocated using the new operator, then it cannot be resized. On the other
hand, the memory is allocated using malloc() function; then, it can be reallocated using realloc()
function.
o The execution time of new is less than the malloc() function as new is a construct, and malloc is
a function.
o The new operator does not return the separate pointer variable; it returns the address of the
newly created object. On the other hand, the malloc() function returns the void pointer which
can be further typecast in a specified type.
In this topic, we are going to learn about the free() function and delete operator in C++.
free() function
The free() function is used in C++ to de-allocate the memory dynamically. It is basically a library
function used in C++, and it is defined in stdlib.h header file. This library function is used when the
pointers either pointing to the memory allocated using malloc() function or Null pointer.
Suppose we have declared a pointer 'ptr', and now, we want to de-allocate its memory:
1. free(ptr);
The above syntax would de-allocate the memory of the pointer variable 'ptr'.
free() parameters
In the above syntax, ptr is a parameter inside the free() function. The ptr is a pointer pointing to the
memory block allocated using malloc(), calloc() or realloc function. This pointer can also be null or a
pointer allocated using malloc but not pointing to any other memory block.
o If the pointer is null, then the free() function will not do anything.
o If the pointer is allocated using malloc, calloc, or realloc, but not pointing to any memory block
then this function will cause undefined behavior.
The free() function does not return any value. Its main function is to free the memory.
1. #include <iostream>
2. #include <cstdlib>
3. using namespace std;
4.
5. int main()
6. {
7. int *ptr;
8. ptr = (int*) malloc(5*sizeof(int));
9. cout << "Enter 5 integer" << endl;
10.
11. for (int i=0; i<5; i++)
12. {
13. // *(ptr+i) can be replaced by ptr[i]
14. cin >>ptr[i];
15. }
16. cout << endl << "User entered value"<< endl;
17.
18. for (int i=0; i<5; i++)
19. {
20. cout <<*(ptr+i) << " ";
21. }
22. free(ptr);
23.
24. /* prints a garbage value after ptr is free */
25. cout << "Garbage Value" << endl;
26.
27. for (int i=0; i<5; i++)
28. {
29. cout << *(ptr+i)<< " ";
30. }
31. return 0;
32. }
1. #include <iostream>
2. #include <cstdlib>
3. using namespace std;
4. int main()
5. {
6. float *ptr; // float pointer declaration
7. ptr=(float*)calloc(1,sizeof(float));
8. *ptr=6.7;
9. std::cout << "The value of *ptr before applying the free() function : " <<*ptr<< std::endl;
10. free(ptr);
11. std::cout << "The value of *ptr after applying the free() function :" <<*ptr<< std::endl;
12. return 0;
13. }
In the above example, we can observe that free() function works with a calloc(). We use the calloc()
function to allocate the memory block to the float pointer ptr. We have assigned a memory block to the
ptr that can have a single float type value.
1. #include <iostream>
2. #include <cstdlib>
3. using namespace std;
4. int main()
5. {
6. int *ptr1=NULL;
7. int *ptr2;
8. int x=9;
9. ptr2=&x;
10. if(ptr1)
11. {
12. std::cout << "Pointer is not Null" << std::endl;
13. }
14. else
15. {
16. cout<<"Ponter is NULL";
17. }
18. free(ptr1);
19. //free(ptr2); // If this statement is executed, then it gives a runtime error.
20. return 0;
21. }
The above code shows how free() function works with a NULL pointer. We have declared two pointers,
i.e., ptr1 and ptr2. We assign a NULL value to the pointer ptr1 and the address of x variable to pointer
ptr2. When we apply the free(ptr1) function to the ptr1, then the memory block assigned to the ptr is
successfully freed. The statement free(ptr2) shows a runtime error as the memory block assigned to
the ptr2 is not allocated using malloc or calloc function.
Output
Delete operator
It is an operator used in C++ programming language, and it is used to de-allocate the memory
dynamically. This operator is mainly used either for those pointers which are allocated using a new
operator or NULL pointer.
Syntax
1. delete pointer_name
For example, if we allocate the memory to the pointer using the new operator, and now we want to
delete it. To delete the pointer, we use the following statement:
1. delete p;
1. delete [] p;
o It is either used to delete the array or non-array objects which are allocated by using the new
keyword.
o To delete the array or non-array object, we use delete[] and delete operator, respectively.
o The new keyword allocated the memory in a heap; therefore, we can say that the delete
operator always de-allocates the memory from the heap
o It does not destroy the pointer, but the value or the memory block, which is pointed by the
pointer is destroyed.
1. #include <iostream>
2. #include <cstdlib>
3. using namespace std;
4.
5. int main()
6. {
7. int *ptr;
8. ptr=new int;
9. *ptr=68;
10. std::cout << "The value of p is : " <<*ptr<< std::endl;
11. delete ptr;
12. std::cout <<"The value after delete is : " <<*ptr<< std::endl;
13. return 0;
14. }
In the above code, we use the new operator to allocate the memory, so we use the delete ptr operator
to destroy the memory block, which is pointed by the pointer ptr.
Output
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int *ptr=new int[5]; // memory allocation using new operator.
6. std::cout << "Enter 5 integers:" << std::endl;
7. for(int i=1;i<=5;i++)
8. {
9. cin>>ptr[i];
10. }
11. std::cout << "Entered values are:" << std::endl;
12. for(int i=1;i<=5;i++)
13. {
14. cout<<*(ptr+i)<<endl;
15. }
16. delete[] ptr; // deleting the memory block pointed by the ptr.
17. std::cout << "After delete, the garbage value:" << std::endl;
18. for(int i=1;i<=5;i++)
19. {
20. cout<<*(ptr+i)<<endl;
21. }
22. return 0;
23. }
Differences between delete and free()
The following are the differences between delete and free() in C++ are:
o The delete is an operator that de-allocates the memory dynamically while the free() is a function
that destroys the memory at the runtime.
o The delete operator is used to delete the pointer, which is either allocated using new operator or
a NULL pointer, whereas the free() function is used to delete the pointer that is either allocated
using malloc(), calloc() or realloc() function or NULL pointer.
o When the delete operator destroys the allocated memory, then it calls the destructor of the
class in C++, whereas the free() function does not call the destructor; it only frees the memory
from the heap.
The major purpose of C++ programming is to introduce the concept of object orientation to the C
programming language.
Object Oriented Programming is a paradigm that provides many concepts such as inheritance, data
binding, polymorphism etc.
The programming paradigm where everything is represented as an object is known as truly object-
oriented programming language. Smalltalk is considered as the first truly object-oriented
programming language.
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the software
development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard,
bike etc. It can be physical and logical.
Class
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
2. OOPs provide data hiding whereas in Procedure-oriented programming language a global data
can be accessed from anywhere.
3. OOPs provide ability to simulate real-world event much more effectively. We can provide the
solution of real word problem if we are using the Object-Oriented Programming language.
Since C++ is an object-oriented language, program is designed using objects and classes in C++.
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.
8.1M
160
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.
C++ Class
In C++, class is a group of similar objects. It is a template from which objects are created. It can have
fields, methods, constructors etc.
Let's see an example of C++ class that has three fields only.
1. class Student
2. {
3. public:
4. int id; //field or data member
5. float salary; //field or data member
6. String name;//field or data member
7. }
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
Let's see another example of C++ class where we are initializing and displaying object through
method.
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. void insert(int i, string n)
8. {
9. id = i;
10. name = n;
11. }
12. void display()
13. {
14. cout<<id<<" "<<name<<endl;
15. }
16. };
17. int main(void) {
18. Student s1; //creating an object of Student
19. Student s2; //creating an object of Student
20. s1.insert(201, "Sonoo");
21. s2.insert(202, "Nakul");
22. s1.display();
23. s2.display();
24. return 0;
25. }
Output:
201 Sonoo
202 Nakul
Let's see another example of C++ class where we are storing and displaying employee information
using method.
1. #include <iostream>
2. using namespace std;
3. class Employee {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. float salary;
8. void insert(int i, string n, float s)
9. {
10. id = i;
11. name = n;
12. salary = s;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1; //creating an object of Employee
21. Employee e2; //creating an object of Employee
22. e1.insert(201, "Sonoo",990000);
23. e2.insert(202, "Nakul", 29000);
24. e1.display();
25. e2.display();
26. return 0;
27. }
Output:
C++ Constructor
In C++, constructor is a special method which is invoked automatically at the time of object creation. It
is used to initialize the data members of new object generally. The constructor in C++ has the same
name as class or structure.
o Default constructor
o Parameterized constructor
A constructor which has no argument is known as default constructor. It is invoked at the time of
creating object.
28M
519
1. #include <iostream>
2. using namespace std;
3. class Employee
4. {
5. public:
6. Employee()
7. {
8. cout<<"Default Constructor Invoked"<<endl;
9. }
10. };
11. int main(void)
12. {
13. Employee e1; //creating an object of Employee
14. Employee e2;
15. return 0;
16. }
Output:
A constructor which has parameters is called parameterized constructor. It is used to provide different
values to distinct objects.
#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
Output:
C++ Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can be defined only
once in a class. Like constructors, it is invoked automatically.
A destructor is defined like constructor. It must have same name as class. But it is prefixed with a tilde
sign (~).
Note: C++ destructor cannot have parameters. Moreover, modifiers can't be applied on destructors.
Let's see an example of constructor and destructor in C++ which is called automatically.
1. #include <iostream>
2. using namespace std;
3. class Employee
4. {
5. public:
6. Employee()
7. {
8. cout<<"Constructor Invoked"<<endl;
9. }
10. ~Employee()
11. {
12. cout<<"Destructor Invoked"<<endl;
13. }
14. };
15. int main(void)
16. {
17. Employee e1; //creating an object of Employee
18. Employee e2; //creating an object of Employee
19. return 0;
20. }
Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
In C++ programming, this is a keyword that refers to the current instance of the class. There can be 3
main usage of this keyword in C++.
Let's see the example of this keyword in C++ that refers to the fields of current class.
1. #include <iostream>
2. using namespace std;
3. class Employee {
4. public:
5. int id; //data member (also instance variable)
6. string name; //data member(also instance variable)
7. float salary;
8. Employee(int id, string name, float salary)
9. {
10. this->id = id;
11. this->name = name;
12. this->salary = salary;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
21. Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
22. e1.display();
23. e2.display();
24. return 0;
25. }
Output:
C++ static
In C++, static is a keyword or modifier that belongs to the type not instance. So instance is not
required to access the static members. In C++, static can be field, method, constructor, class,
properties, operator and event.
Memory efficient: Now we don't need to create instance for accessing the static members, so it saves
memory. Moreover, it belongs to the type, so it will not get memory each time when instance is
created.
A field which is declared as static is called static field. Unlike instance field which gets memory each
time whenever you create object, there is only one copy of static field created in the memory. It is
shared to all the objects.
It is used to refer the common property of all objects such as rateOfInterest in case of Account,
companyName in case of Employee etc.
1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. int accno; //data member (also instance variable)
6. string name; //data member(also instance variable)
7. static float rateOfInterest;
8. Account(int accno, string name)
9. {
10. this->accno = accno;
11. this->name = name;
12. }
13. void display()
14. {
15. cout<<accno<< "<<name<< " "<<rateOfInterest<<endl;
16. }
17. };
18. float Account::rateOfInterest=6.5;
19. int main(void) {
20. Account a1 =Account(201, "Sanjay"); //creating an object of Employee
21. Account a2=Account(202, "Nakul"); //creating an object of Employee
22. a1.display();
23. a2.display();
24. return 0;
25. }
Output:
Let's see another example of static keyword in C++ which counts the objects.
1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. int accno; //data member (also instance variable)
6. string name;
7. static int count;
8. Account(int accno, string name)
9. {
10. this->accno = accno;
11. this->name = name;
12. count++;
13. }
14. void display()
15. {
16. cout<<accno<<" "<<name<<endl;
17. }
18. };
19. int Account::count=0;
20. int main(void) {
21. Account a1 =Account(201, "Sanjay"); //creating an object of Account
22. Account a2=Account(202, "Nakul");
23. Account a3=Account(203, "Ranjana");
24. a1.display();
25. a2.display();
26. a3.display();
27. cout<<"Total Objects are: "<<Account::count;
28. return 0;
29. }
Output:
201 Sanjay
202 Nakul
203 Ranjana
Total Objects are: 3
C++ Structs
In C++, classes and structs are blueprints that are used to create the instance of a class. Structs are
used for lightweight objects such as Rectangle, color, Point, etc.
Unlike class, structs in C++ are value type than reference type. It is useful if you have data that is not
intended to be modified after creation of struct.
C++ Structure is a collection of different data types. It is similar to the class that holds different types
of data.
1. struct structure_name
2. {
3. // member declarations.
4. }
In the above declaration, a structure is declared by preceding the struct keyword followed by the
identifier(structure name). Inside the curly braces, we can declare the member variables of different
types. Consider the following situation:
1. struct Student
2. {
3. char name[20];
4. int id;
5. int age;
6. }
In the above case, Student is a structure contains three variables name, id, and age. When the
structure is declared, no memory is allocated. When the variable of a structure is created, then the
memory is allocated. Let's understand this scenario.
Student s;
Here, s is a structure variable of type Student. When the structure variable is created, the memory will
be allocated. Student structure contains one char variable and two integer variable. Therefore, the
memory for one char variable is 1 byte and two ints will be 2*4 = 8. The total memory occupied by the
s variable is 9 byte.
The variable of the structure can be accessed by simply using the instance of the structure followed by
the dot (.) operator and then the field of the structure.
For example:
1. s.id = 4;
In the above statement, we are accessing the id field of the structure Student by using
the dot(.) operator and assigns the value 4 to the id field.
Let's see a simple example of struct Rectangle which has two data members width and height.
1. #include <iostream>
2. using namespace std;
3. struct Rectangle
4. {
5. int width, height;
6.
7. };
8. int main(void) {
9. struct Rectangle rec;
10. rec.width=8;
11. rec.height=5;
12. cout<<"Area of Rectangle is: "<<(rec.width * rec.height)<<endl;
13. return 0;
14. }
Let's see another example of struct where we are using the constructor to initialize data and method to
calculate the area of rectangle.
1. #include <iostream>
2. using namespace std;
3. struct Rectangle {
4. int width, height;
5. Rectangle(int w, int h)
6. {
7. width = w;
8. height = h;
9. }
10. void areaOfRectangle() {
11. cout<<"Area of Rectangle is: "<<(width*height); }
12. };
13. int main(void) {
14. struct Rectangle rec=Rectangle(4,6);
15. rec.areaOfRectangle();
16. return 0;
17. }
Structure Class
If access specifier is not declared explicitly, then by default If access specifier is not declared explicitly, th
access specifier will be public. access specifier will be private.
The instance of the structure is known as "Structure The instance of the class is known as "Object o
variable".
C++ Enumeration
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The C++ enum constants are static
and final implicitly.
C++ Enums can be thought of as classes that have fixed set of constants.
o enum may implement many interfaces but cannot extend any class because it internally
extends Enum class
Let's see the simple example of enum data type used in C++ program.
1. #include <iostream>
2. using namespace std;
3. enum week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
4. int main()
5. {
6. week day;
7. day = Friday;
8. cout << "Day: " << day+1<<endl;
9. return 0;
10. }
C++ Friend function
If a function is defined as a friend function in C++, then the protected and private data of a class can
be accessed using the function.
By using the keyword friend compiler knows the given function is a friend function.
For accessing the data, the declaration of a friend function should be done inside the body of a class
starting with the keyword friend.
1. class class_name
2. {
3. friend data_type function_name(argument/s); // syntax of friend function.
4. };
In the above declaration, the friend function is preceded by the keyword friend. The function can be
defined anywhere in the program like a normal C++ function. The function definition does not use
either the keyword friend or scope resolution operator.
Characteristics of a Friend function:
o The function is not in the scope of the class to which it has been declared as a friend.
o It cannot be called using the object as it is not in the scope of that class.
o It cannot access the member names directly and has to use an object name and dot
membership operator with the member name.
Let's see the simple example of C++ friend function used to print the length of a box.
1. #include <iostream>
2. using namespace std;
3. class Box
4. {
5. private:
6. int length;
7. public:
8. Box(): length(0) { }
9. friend int printLength(Box); //friend function
10. };
11. int printLength(Box b)
12. {
13. b.length += 10;
14. return b.length;
15. }
16. int main()
17. {
18. Box b;
19. cout<<"Length of box: "<< printLength(b)<<endl;
20. return 0;
21. }
Let's see a simple example when the function is friendly to two classes.
1. #include <iostream>
2. using namespace std;
3. class B; // forward declarartion.
4. class A
5. {
6. int x;
7. public:
8. void setdata(int i)
9. {
10. x=i;
11. }
12. friend void min(A,B); // friend function.
13. };
14. class B
15. {
16. int y;
17. public:
18. void setdata(int i)
19. {
20. y=i;
21. }
22. friend void min(A,B); // friend function
23. };
24. void min(A a,B b)
25. {
26. if(a.x<=b.y)
27. std::cout << a.x << std::endl;
28. else
29. std::cout << b.y << std::endl;
30. }
31. int main()
32. {
33. A a;
34. B b;
35. a.setdata(10);
36. b.setdata(20);
37. min(a,b);
38. return 0;
39. }
In the above example, min() function is friendly to two classes, i.e., the min() function can access the
private members of both the classes A and B.
A friend class can access both private and protected members of the class in which it has been
declared as friend.
1. #include <iostream>
2.
3. using namespace std;
4.
5. class A
6. {
7. int x =5;
8. friend class B; // friend class.
9. };
10. class B
11. {
12. public:
13. void display(A &a)
14. {
15. cout<<"value of x is : "<<a.x;
16. }
17. };
18. int main()
19. {
20. A a;
21. B b;
22. b.display(a);
23. return 0;
24. }
In the above example, class B is declared as a friend inside the class A. Therefore, B is a friend of class
A. Class B can access the private members of class A
C++ Inheritance
In C++, inheritance is a process in which one object acquires all the properties and behaviors of its
parent object automatically. In such way, you can reuse, extend or modify the attributes and behaviors
which are defined in other class.
In C++, the class which inherits the members of another class is called derived class and the class
whose members are inherited is called base class. The derived class is the specialized class for the
base class.
Code reusability: Now you can reuse the members of your parent class. So, there is no need to define
the member again. So less code is required in the class.
Types Of Inheritance
28M
519
Prime Ministers of India | List of Prime Minister of India (1947-2020)
o Single inheritance
o Multiple inheritance
o Hierarchical inheritance
o Multilevel inheritance
o Hybrid inheritance
Derived Classes
A Derived class is defined as the class derived from the base class.
Where,
visibility mode: The visibility mode specifies whether the features of the base class are publicly
inherited or privately inherited. It can be public or private.
o When the base class is privately inherited by the derived class, public members of the base
class becomes the private members of the derived class. Therefore, the public members of the
base class are not accessible by the objects of the derived class only by the member functions
of the derived class.
o When the base class is publicly inherited by the derived class, public members of the base class
also become the public members of the derived class. Therefore, the public members of the
base class are accessible by the objects of the derived class as well as by the member functions
of the base class.
Note:
Single inheritance is defined as the inheritance in which a derived class is inherited from the only one
base class.
Where 'A' is the base class, and 'B' is the derived class.
When one class inherits another class, it is known as single level inheritance. Let's see the example of
single level inheritance which inherits the fields only.
1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. float salary = 60000;
6. };
7. class Programmer: public Account {
8. public:
9. float bonus = 5000;
10. };
11. int main(void) {
12. Programmer p1;
13. cout<<"Salary: "<<p1.salary<<endl;
14. cout<<"Bonus: "<<p1.bonus<<endl;
15. return 0;
16. }
In the above example, Employee is the base class and Programmer is the derived class.
1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat() {
6. cout<<"Eating..."<<endl;
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void bark(){
13. cout<<"Barking...";
14. }
15. };
16. int main(void) {
17. Dog d1;
18. d1.eat();
19. d1.bark();
20. return 0;
21. }
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. int a = 4;
6. int b = 5;
7. public:
8. int mul()
9. {
10. int c = a*b;
11. return c;
12. }
13. };
14.
15. class B : private A
16. {
17. public:
18. void display()
19. {
20. int result = mul();
21. std::cout <<"Multiplication of a and b is : "<<result<< std::endl;
22. }
23. };
24. int main()
25. {
26. B b;
27. b.display();
28.
29. return 0;
30. }
In the above example, class A is privately inherited. Therefore, the mul() function of class 'A' cannot be
accessed by the object of class B. It can only be accessed by the member function of class B.
The private member is not inheritable. If we modify the visibility mode by making it public, but this
takes away the advantage of data hiding.
C++ introduces a third visibility modifier, i.e., protected. The member which is declared as protected
will be accessible to all the member functions within the class as well as the class immediately derived
from it.
o Public: When the member is declared as public, it is accessible to all the functions of the
program.
o Private: When the member is declared as private, it is accessible within the class only.
o Protected: When the member is declared as protected, it is accessible within its own class as
well as the class immediately derived from it.
When one class inherits another class which is further inherited by another class, it is known as multi
level inheritance in C++. Inheritance is transitive so the last derived class acquires all the members of
all its base classes.
1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat() {
6. cout<<"Eating..."<<endl;
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void bark(){
13. cout<<"Barking..."<<endl;
14. }
15. };
16. class BabyDog: public Dog
17. {
18. public:
19. void weep() {
20. cout<<"Weeping...";
21. }
22. };
23. int main(void) {
24. BabyDog d1;
25. d1.eat();
26. d1.bark();
27. d1.weep();
28. return 0;
29. }
Multiple inheritance is the process of deriving a new class that inherits the attributes from two or
more classes.
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. protected:
6. int a;
7. public:
8. void get_a(int n)
9. {
10. a = n;
11. }
12. };
13.
14. class B
15. {
16. protected:
17. int b;
18. public:
19. void get_b(int n)
20. {
21. b = n;
22. }
23. };
24. class C : public A,public B
25. {
26. public:
27. void display()
28. {
29. std::cout << "The value of a is : " <<a<< std::endl;
30. std::cout << "The value of b is : " <<b<< std::endl;
31. cout<<"Addition of a and b is : "<<a+b;
32. }
33. };
34. int main()
35. {
36. C c;
37. c.get_a(10);
38. c.get_b(20);
39. c.display();
40.
41. return 0;
42. }
In the above example, class 'C' inherits two base classes 'A' and 'B' in a public mode.
Ambiguity can be occurred in using the multiple inheritance when a function with the same name
occurs in more than one base class.
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. public:
6. void display()
7. {
8. std::cout << "Class A" << std::endl;
9. }
10. };
11. class B
12. {
13. public:
14. void display()
15. {
16. std::cout << "Class B" << std::endl;
17. }
18. };
19. class C : public A, public B
20. {
21. void view()
22. {
23. display();
24. }
25. };
26. int main()
27. {
28. C c;
29. c.display();
30. return 0;
31. }
o The above issue can be resolved by using the class resolution operator with the function. In the
above example, the derived class code can be rewritten as:
In the above case, the function of the derived class overrides the method of the base class. Therefore,
call to the display() function will simply call the function defined in the derived class. If we want to
invoke the base class function, we can use the class resolution operator.
1. int main()
2. {
3. B b;
4. b.display(); // Calling the display() function of B class.
5. b.B :: display(); // Calling the display() function defined in B class.
6. }
Hierarchical inheritance is defined as the process of deriving more than one class from a base class.
1. class A
2. {
3. // body of the class A.
4. }
5. class B : public A
6. {
7. // body of class B.
8. }
9. class C : public A
10. {
11. // body of class C.
12. }
13. class D : public A
14. {
15. // body of class D.
16. }
1. #include <iostream>
2. using namespace std;
3. class Shape // Declaration of base class.
4. {
5. public:
6. int a;
7. int b;
8. void get_data(int n,int m)
9. {
10. a= n;
11. b = m;
12. }
13. };
14. class Rectangle : public Shape // inheriting Shape class
15. {
16. public:
17. int rect_area()
18. {
19. int result = a*b;
20. return result;
21. }
22. };
23. class Triangle : public Shape // inheriting Shape class
24. {
25. public:
26. int triangle_area()
27. {
28. float result = 0.5*a*b;
29. return result;
30. }
31. };
32. int main()
33. {
34. Rectangle r;
35. Triangle t;
36. int length,breadth,base,height;
37. std::cout << "Enter the length and breadth of a rectangle: " << std::endl;
38. cin>>length>>breadth;
39. r.get_data(length,breadth);
40. int m = r.rect_area();
41. std::cout << "Area of the rectangle is : " <<m<< std::endl;
42. std::cout << "Enter the base and height of the triangle: " << std::endl;
43. cin>>base>>height;
44. t.get_data(base,height);
45. float n = t.triangle_area();
46. std::cout <<"Area of the triangle is : " << n<<std::endl;
47. return 0;
48. }
C++ Aggregation (HAS-A Relationship)
In C++, aggregation is a process in which one class defines another class as any entity reference. It is
another way to reuse the class. It is a form of association that represents HAS-A relationship.
Let's see an example of aggregation where Employee class has the reference of Address class as data
member. In such way, it can reuse the members of Address class.
1. #include <iostream>
2. using namespace std;
3. class Address {
4. public:
5. string addressLine, city, state;
6. Address(string addressLine, string city, string state)
7. {
8. this->addressLine = addressLine;
9. this->city = city;
10. this->state = state;
11. }
12. };
13. class Employee
14. {
15. private:
16. Address* address; //Employee HAS-A Address
17. public:
18. int id;
19. string name;
20. Employee(int id, string name, Address* address)
21. {
22. this->id = id;
23. this->name = name;
24. this->address = address;
25. }
26. void display()
27. {
28. cout<<id <<" "<<name<< " "<<
29. address->addressLine<< " "<< address->city<< " "<<address->state<<endl;
30. }
31. };
32. int main(void) {
33. Address a1= Address("C-146, Sec-15","Noida","UP");
34. Employee e1 = Employee(101,"Nakul",&a1);
35. e1.display();
36. return 0;
37. }
C++ Polymorphism
The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms. It is a
greek word. In object-oriented programming, we use 3 main concepts: inheritance, encapsulation, and
polymorphism.
Let's consider a real-life example of polymorphism. A lady behaves like a teacher in a classroom,
mother or daughter in a home and customer in a market. Here, a single person is behaving differently
according to the situations.
o Compile time polymorphism: The overloaded functions are invoked by matching the type and
number of arguments. This information is available at the compile time and, therefore, compiler
selects the appropriate function at the compile time. It is achieved by function overloading and
operator overloading which is also known as static binding or early binding. Now, let's consider
the case where function name and prototype is same.
In the above case, the prototype of display() function is the same in both the base and derived class.
Therefore, the static binding cannot be applied. It would be great if the appropriate function is selected
at the run time. This is known as run time polymorphism.
40M
761
o Run time polymorphism: Run time polymorphism is achieved when the object's method is
invoked at the run time instead of compile time. It is achieved by method overriding which is
also known as dynamic binding or late binding.
The function to be invoked is known at the The function to be invoked is known at the
compile time. run time.
It is also known as overloading, early binding and It is also known as overriding, Dynamic
static binding. binding and late binding.
1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat(){
6. cout<<"Eating...";
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void eat()
13. { cout<<"Eating bread...";
14. }
15. };
16. int main(void) {
17. Dog d = Dog();
18. d.eat();
19. return 0;
20. }
Output:
Eating bread...
Let's see another example of run time polymorphism in C++ where we are having two derived classes.
1. #include <iostream>
2. using namespace std;
3. class Shape { // base class
4. public:
5. virtual void draw(){ // virtual function
6. cout<<"drawing..."<<endl;
7. }
8. };
9. class Rectangle: public Shape // inheriting Shape class.
10. {
11. public:
12. void draw()
13. {
14. cout<<"drawing rectangle..."<<endl;
15. }
16. };
17. class Circle: public Shape // inheriting Shape class.
18.
19. {
20. public:
21. void draw()
22. {
23. cout<<"drawing circle..."<<endl;
24. }
25. };
26. int main(void) {
27. Shape *s; // base class pointer.
28. Shape sh; // base class object.
29. Rectangle rec;
30. Circle cir;
31. s=&sh;
32. s->draw();
33. s=&rec;
34. s->draw();
35. s=?
36. s->draw();
37. }
Runtime Polymorphism can be achieved by data members in C++. Let's see an example where we are
accessing the field by reference variable which refers to the instance of derived class.
1. #include <iostream>
2. using namespace std;
3. class Animal { // base class declaration.
4. public:
5. string color = "Black";
6. };
7. class Dog: public Animal // inheriting Animal class.
8. {
9. public:
10. string color = "Grey";
11. };
12. int main(void) {
13. Animal d= Dog();
14. cout<<d.color;
15. }
C++ Overloading (Function and Operator)
If we create two or more members having the same name but different in number or type of
parameter, it is known as C++ overloading. In C++, we can overload:
o methods,
o constructors, and
o indexed properties
o Function overloading
o Operator overloading
Function Overloading is defined as the process of having two or more function with the same name, but
different in parameters is known as function overloading in C++. In function overloading, the function is
redefined by using either different types of arguments or a different number of arguments. It is only
through these differences compiler can differentiate between the functions.
The advantage of Function overloading is that it increases the readability of the program because you
don't need to use different names for the same action.
00:00/05:45
Let's see the simple example of function overloading where we are changing number of arguments of
add() method.
// program of function overloading when number of arguments vary.
1. #include <iostream>
2. using namespace std;
3. class Cal {
4. public:
5. static int add(int a,int b){
6. return a + b;
7. }
8. static int add(int a, int b, int c)
9. {
10. return a + b + c;
11. }
12. };
13. int main(void) {
14. Cal C; // class object declaration.
15. cout<<C.add(10, 20)<<endl;
16. cout<<C.add(12, 20, 23);
17. return 0;
18. }
Let's see the simple example when the type of the arguments vary.
1. #include<iostream>
2. using namespace std;
3. int mul(int,int);
4. float mul(float,int);
5.
6.
7. int mul(int a,int b)
8. {
9. return a*b;
10. }
11. float mul(double x, int y)
12. {
13. return x*y;
14. }
15. int main()
16. {
17. int r1 = mul(6,7);
18. float r2 = mul(0.2,3);
19. std::cout << "r1 is : " <<r1<< std::endl;
20. std::cout <<"r2 is : " <<r2<< std::endl;
21. return 0;
22. }
When the compiler is unable to decide which function is to be invoked among the overloaded function,
this situation is known as function overloading.
When the compiler shows the ambiguity error, the compiler does not run the program.
o Type Conversion.
o Type Conversion:
1. #include<iostream>
2. using namespace std;
3. void fun(int);
4. void fun(float);
5. void fun(int i)
6. {
7. std::cout << "Value of i is : " <<i<< std::endl;
8. }
9. void fun(float j)
10. {
11. std::cout << "Value of j is : " <<j<< std::endl;
12. }
13. int main()
14. {
15. fun(12);
16. fun(1.2);
17. return 0;
18. }
The above example shows an error "call of overloaded 'fun(double)' is ambiguous". The fun(10)
will call the first function. The fun(1.2) calls the second function according to our prediction. But, this
does not refer to any function as in C++, all the floating point constants are treated as double not as a
float. If we replace float to double, the program works. Therefore, this is a type conversion from float to
double.
1. #include<iostream>
2. using namespace std;
3. void fun(int);
4. void fun(int,int);
5. void fun(int i)
6. {
7. std::cout << "Value of i is : " <<i<< std::endl;
8. }
9. void fun(int a,int b=9)
10. {
11. std::cout << "Value of a is : " <<a<< std::endl;
12. std::cout << "Value of b is : " <<b<< std::endl;
13. }
14. int main()
15. {
16. fun(12);
17.
18. return 0;
19. }
The above example shows an error "call of overloaded 'fun(int)' is ambiguous". The fun(int a, int b=9)
can be called in two ways: first is by calling the function with one argument, i.e., fun(12) and another
way is calling the function with two arguments, i.e., fun(4,5). The fun(int i) function is invoked with one
argument. Therefore, the compiler could not be able to select among fun(int i) and fun(int a,int b=9).
1. #include <iostream>
2. using namespace std;
3. void fun(int);
4. void fun(int &);
5. int main()
6. {
7. int a=10;
8. fun(a); // error, which f()?
9. return 0;
10. }
11. void fun(int x)
12. {
13. std::cout << "Value of x is : " <<x<< std::endl;
14. }
15. void fun(int &b)
16. {
17. std::cout << "Value of b is : " <<b<< std::endl;
18. }
The above example shows an error "call of overloaded 'fun(int&)' is ambiguous". The first function
takes one integer argument and the second function takes a reference parameter as an argument. In
this case, the compiler does not know which function is needed by the user as there is no syntactical
difference between the fun(int) and fun(int &).
The advantage of Operators overloading is to perform different operations on the same operand.
o Sizeof
o member selector(.)
o ternary operator(?:)
Where the return type is the type of value returned by the function.
operator op is an operator function where op is the operator being overloaded, and the operator is the
keyword.
o The overloaded operator contains atleast one operand of the user-defined data type.
o We cannot use friend function to overload certain operators. However, the member function can
be used to overload those operators.
o When unary operators are overloaded through a member function take no explicit arguments,
but, if they are overloaded by a friend function, takes one argument.
o When binary operators are overloaded through a member function takes one explicit argument,
and if they are overloaded through a friend function takes two explicit arguments.
Let's see the simple example of operator overloading in C++. In this example, void operator ++ ()
operator function is defined (inside Test class).
1. #include <iostream>
2. using namespace std;
3. class Test
4. {
5. private:
6. int num;
7. public:
8. Test(): num(8){}
9. void operator ++() {
10. num = num+2;
11. }
12. void Print() {
13. cout<<"The Count is: "<<num;
14. }
15. };
16. int main()
17. {
18. Test tt;
19. ++tt; // calling of a function "void operator ++()"
20. tt.Print();
21. return 0;
22. }
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5.
6. int x;
7. public:
8. A(){}
9. A(int i)
10. {
11. x=i;
12. }
13. void operator+(A);
14. void display();
15. };
16.
17. void A :: operator+(A a)
18. {
19.
20. int m = x+a.x;
21. cout<<"The result of the addition of two objects is : "<<m;
22.
23. }
24. int main()
25. {
26. A a1(5);
27. A a2(4);
28. a1+a2;
29. return 0;
30. }
C++ Function Overriding
If derived class defines same function as defined in its base class, it is known as function overriding in
C++. It is used to achieve runtime polymorphism. It enables you to provide specific implementation of
the function which is already provided by its base class.
Let's see a simple example of Function overriding in C++. In this example, we are overriding the eat()
function.
1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat(){
6. cout<<"Eating...";
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void eat()
13. {
14. cout<<"Eating bread...";
15. }
16. };
17. int main(void) {
18. Dog d = Dog();
19. d.eat();
20. return 0;
21. }
C++ virtual function
o A C++ virtual function is a member function in the base class that you redefine in a derived
class. It is declared using the virtual keyword.
o It is used to tell the compiler to perform dynamic linkage or late binding on the function.
o There is a necessity to use the single pointer to refer to all the objects of the different classes.
So, we create the pointer to the base class that refers to all the derived objects. But, when base
class pointer contains the address of the derived class object, always executes the base class
function. This issue can only be resolved by using the 'virtual' function.
o When the function is made virtual, C++ determines which function is to be invoked at the
runtime based on the type of the object pointed by the base class pointer.
In late binding function call is resolved during runtime. Therefore compiler determines the type of
object at runtime, and then binds the function call.
o A virtual function must be defined in the base class, even though it is not used.
o The prototypes of a virtual function of the base class and all the derived classes must be
identical. If the two functions with the same name but different prototypes, C++ will consider
them as the overloaded functions.
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. int x=5;
6. public:
7. void display()
8. {
9. std::cout << "Value of x is : " << x<<std::endl;
10. }
11. };
12. class B: public A
13. {
14. int y = 10;
15. public:
16. void display()
17. {
18. std::cout << "Value of y is : " <<y<< std::endl;
19. }
20. };
21. int main()
22. {
23. A *a;
24. B b;
25. a = &b;
26. a->display();
27. return 0;
28. }
In the above example, * a is the base class pointer. The pointer can only access the base class
members but not the members of the derived class. Although C++ permits the base pointer to point to
any object derived from the base class, it cannot directly access the members of the derived class.
Therefore, there is a need for virtual function which allows the base pointer to access the members of
the derived class.
Let's see the simple example of C++ virtual function used to invoked the derived class in a program.
1. #include <iostream>
2. {
3. public:
4. virtual void display()
5. {
6. cout << "Base class is invoked"<<endl;
7. }
8. };
9. class B:public A
10. {
11. public:
12. void display()
13. {
14. cout << "Derived Class is invoked"<<endl;
15. }
16. };
17. int main()
18. {
19. A* a; //pointer of base class
20. B b; //object of derived class
21. a = &b;
22. a->display(); //Late Binding occurs
23. }
o A virtual function is not used for performing any task. It only serves as a placeholder.
o When the function has no definition, such function is known as "do-nothing" function.
o The "do-nothing" function is known as a pure virtual function. A pure virtual function is a
function declared in the base class that has no definition relative to the base class.
o A class containing the pure virtual function cannot be used to declare the objects of its own,
such classes are known as abstract base classes.
o The main objective of the base class is to provide the traits to the derived classes and to create
the base pointer used for achieving the runtime polymorphism.
1. #include <iostream>
2. using namespace std;
3. class Base
4. {
5. public:
6. virtual void show() = 0;
7. };
8. class Derived : public Base
9. {
10. public:
11. void show()
12. {
13. std::cout << "Derived class is derived from the base class." << std::endl;
14. }
15. };
16. int main()
17. {
18. Base *bptr;
19. //Base b;
20. Derived d;
21. bptr = &d;
22. bptr->show();
23. return 0;
24. }
Interfaces in C++ (Abstract Classes)
Abstract classes are the way to achieve abstraction in C++. Abstraction in C++ is the process to hide
the internal details and showing functionality only. Abstraction can be achieved by two ways:
1. Abstract class
2. Interface
Abstract class and interface both can have abstract methods which are necessary for abstraction.
In C++ class is made abstract by declaring at least one of its functions as <>strong>pure virtual
function. A pure virtual function is specified by placing "= 0" in its declaration. Its implementation must
be provided by derived classes.
Let's see an example of abstract class in C++ which has one abstract method draw(). Its
implementation is provided by derived classes: Rectangle and Circle. Both classes have different
implementation.
1. #include <iostream>
2. using namespace std;
3. class Shape
4. {
5. public:
6. virtual void draw()=0;
7. };
8. class Rectangle : Shape
9. {
10. public:
11. void draw()
12. {
13. cout < <"drawing rectangle..." < <endl;
14. }
15. };
16. class Circle : Shape
17. {
18. public:
19. void draw()
20. {
21. cout <<"drawing circle..." < <endl;
22. }
23. };
24. int main( ) {
25. Rectangle rec;
26. Circle cir;
27. rec.draw();
28. cir.draw();
29. return 0;
30. }
Data Abstraction in C++
o Data Abstraction is a process of providing only the essential details to the outside world and
hiding the internal details, i.e., representing only the essential details in the program.
o Data Abstraction is a programming technique that depends on the seperation of the interface
and implementation details of the program.
o Let's take a real life example of AC, which can be turned ON or OFF, change the temperature,
change the mode, and other external components such as fan, swing. But, we don't know the
internal details of the AC, i.e., how it works internally. Thus, we can say that AC seperates the
implementation details from the external interface.
o C++ provides a great level of abstraction. For example, pow() function is used to calculate the
power of a number without knowing the algorithm the function follows.
In C++ program if we implement class with private and public members then it is an example of data
abstraction.
Abstraction using classes: An abstraction can be achieved using classes. A class is used to group all
the data members and member functions into a single unit by using the access specifiers. A class has
the responsibility to determine which data member is to be visible outside and which is not.
Abstraction in header files: An another type of abstraction is header file. For example, pow()
function available is used to calculate the power of a number without actually knowing which algorithm
function uses to calculate the power. Thus, we can say that header files hides all the implementation
details from the user.
o Public specifier: When the members are declared as public, members can be accessed
anywhere from the program.
o Private specifier: When the members are declared as private, members can only be accessed
only by the member functions of the class.
1. #include <iostream>
2. #include<math.h>
3. using namespace std;
4. int main()
5. {
6. int n = 4;
7. int power = 3;
8. int result = pow(n,power); // pow(n,power) is the power function
9. std::cout << "Cube of n is : " <<result<< std::endl;
10. return 0;
11. }
In the above example, pow() function is used to calculate 4 raised to the power 3. The pow() function is
present in the math.h header file in which all the implementation details of the pow() function is
hidden.
1. #include <iostream>
2. using namespace std;
3. class Sum
4. {
5. private: int x, y, z; // private variables
6. public:
7. void add()
8. {
9. cout<<"Enter two numbers: ";
10. cin>>x>>y;
11. z= x+y;
12. cout<<"Sum of two number is: "<<z<<endl;
13. }
14. };
15. int main()
16. {
17. Sum sm;
18. sm.add();
19. return 0;
20. }
In the above example, abstraction is achieved using classes. A class 'Sum' contains the private
members x, y and z are only accessible by the member functions of the class.
Advantages Of Abstraction:
o Implementation details of the class are protected from the inadvertent user level errors.
o Data Abstraction avoids the code duplication, i.e., programmer does not have to undergo the
same tasks every time to perform the similar operation.
o The main aim of the data abstraction is to reuse the code and the proper partitioning of the
code across the classes.
o Internal implementation can be changed without affecting the user level code.
C++ Strings
In C++, string is an object of std::string class that represents sequence of characters. We can perform
many operations on strings such as concatenation, comparison, conversion etc.
Let's see the simple example of string comparison using strcmp() function.
39M
822
C++ vs Java
1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4. int main ()
5. {
6. char key[] = "mango";
7. char buffer[50];
8. do {
9. cout<<"What is my favourite fruit? ";
10. cin>>buffer;
11. } while (strcmp (key,buffer) != 0);
12. cout<<"Answer is correct!!"<<endl;
13. return 0;
14. }
Let's see the simple example of string concatenation using strcat() function.
1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4. int main()
5. {
6. char key[25], buffer[25];
7. cout << "Enter the key string: ";
8. cin.getline(key, 25);
9. cout << "Enter the buffer string: ";
10. cin.getline(buffer, 25);
11. strcat(key, buffer);
12. cout << "Key = " << key << endl;
13. cout << "Buffer = " << buffer<<endl;
14. return 0;
15. }
Let's see the simple example of copy the string using strcpy() function.
1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4. int main()
5. {
6. char key[25], buffer[25];
7. cout << "Enter the key string: ";
8. cin.getline(key, 25);
9. strcpy(buffer, key);
10. cout << "Key = "<< key << endl;
11. cout << "Buffer = "<< buffer<<endl;
12. return 0;
13. }
C++ String Length Example
Let's see the simple example of finding the string length using strlen() function.
1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4. int main()
5. {
6. char ary[] = "Welcome to C++ Programming";
7. cout << "Length of String = " << strlen(ary)<<endl;
8. return 0;
9. }
Function Description
void swap(string& str) It is used to swap the values of two string objects.
string& replace(int pos,int It replaces portion of the string that begins at character position pos a
len,string& str) characters.
string& append(const string& str) It adds new characters at the end of another string object.
char& at(int pos) It is used to access an individual character at specified position pos.
int find(string& str,int pos,int n) It is used to find the string specified in the parameter.
int find_first_of(string& str,int It is used to find the first occurrence of the specified sequence.
pos,int n)
int find_first_not_of(string& str,int It is used to search the string for the first character that does not matc
pos,int n ) the characters specified in the string.
int find_last_of(string& str,int It is used to search the string for the last character of specified sequence
pos,int n)
int find_last_not_of(string& str,int It searches for the last character that does not match with the specified s
pos)
string& insert() It inserts a new character before the character indicated by the position
void push_back(char ch) It adds a new character ch at the end of the string.
void shrink_to_fit() It reduces the capacity and makes it equal to the size of the string.
char* c_str() It returns pointer to an array that contains null terminated sequence of c
allocator_type get_allocator(); It returns the allocated object associated with the string.
Exception Handling in C++ is a process to handle runtime errors. We perform exception handling so
the normal flow of the application can be maintained even after runtime errors.
In C++, exception is an event or object which is thrown at runtime. All exceptions are derived from
std::exception class. It is a runtime error which can be handled. If we don't handle the exception, it
prints exception message and terminates the program.
Advantage
It maintains the normal flow of the application. In such case, rest of the code is executed even after
exception.
In C++ standard exceptions are defined in <exception> class that we can use inside our programs. The
arrangement of parent-child class hierarchy is shown below:
40.5M
844
Exception Description
o try
o catch, and
o throw
Moreover, we can create user-defined exception which we will learn in next chapters.
C++ try/catch
In C++ programming, exception handling is performed using try/catch statement. The C++ try
block is used to place the code that may occur exception. The catch block is used to handle the
exception.
1. #include <iostream>
2. using namespace std;
3. float division(int x, int y) {
4. return (x/y);
5. }
6. int main () {
7. int i = 50;
8. int j = 0;
9. float k = 0;
10. k = division(i, j);
11. cout << k << endl;
12. return 0;
13. }
1. #include <iostream>
2. using namespace std;
3. float division(int x, int y) {
4. if( y == 0 ) {
5. throw "Attempted to divide by zero!";
6. }
7. return (x/y);
8. }
9. int main () {
10. int i = 25;
11. int j = 0;
12. float k = 0;
13. try {
14. k = division(i, j);
15. cout << k << endl;
16. }catch (const char* e) {
17. cerr << e << endl;
18. }
19. return 0;
20. }
C++ User-Defined Exceptions
The new exception can be defined by overriding and inheriting exception class functionality.
Let's see the simple example of user-defined exception in which std::exception class is used to define
the exception.
1. #include <iostream>
2. #include <exception>
3. using namespace std;
4. class MyException : public exception{
5. public:
6. const char * what() const throw()
7. {
8. return "Attempted to divide by zero!\n";
9. }
10. };
11. int main()
12. {
13. try
14. {
15. int x, y;
16. cout << "Enter the two numbers : \n";
17. cin >> x >> y;
18. if (y == 0)
19. {
20. MyException z;
21. throw z;
22. }
23. else
24. {
25. cout << "x / y = " << x/y << endl;
26. }
27. }
28. catch(exception& e)
29. {
30. cout << e.what();
31. }
32. }