UNIT - I - Final Print
UNIT - I - Final Print
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 Oriented programming is a programming style that is associated with the concept of Class,
Objects and various other concepts revolving around these two, like Inheritance, Polymorphism,
Abstraction, Encapsulation etc.
OOPs (Object Oriented Programming System)
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
Inheritance
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.
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.
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++ History
History of C++ language is interesting to know. Here we are going to discuss brief history of C+
+ language.
C++ programming language was developed in 1980 by Bjarne Stroustrup at bell laboratories of
AT&T (American Telephone & Telegraph), located in U.S.A.
Bjarne Stroustrup is known as the founder of C++ language.
It was develop for adding a feature of OOP (Object Oriented Programming) in C without
significantly changing the C component.
C++ supports the object-oriented programming, the four major pillar of object-oriented
programming (OOPs) used in C++ are:
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
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:
#include <iostream.h>
#include<conio.h>
void main() {
clrscr();
cout << "Welcome to C++ Programming.";
getch();
}
#include<iostream.h> includes the standard input output library functions. It
provides cin and cout methods for reading from input and writing to output respectively.
#include <conio.h> includes the console input output library functions. The getch()
function is defined in conio.h file.
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.
File: main.cpp
#include <iostream>
using namespace std;
int main()
{
cout << "Hello C++ Programming";
return 0;
}
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.
I/O Library Header Files
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
#include <iostream>
using namespace std;
int main( )
{
char ary[] = "Welcome to C++ tutorial";
cout << "Value of ary is: " << ary << endl;
}
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.
Output:
The endl is a predefined object of ostream class. It is used to insert a new line characters and
flushes the stream.
#include <iostream>
using namespace std;
int main( )
{
cout << "C++ Tutorial";
cout << " Java"<<endl;
cout << "End of line"<<endl;
}
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.
type variable_list;
The example of declaring variable is given below:
int x;
float y;
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.
int a;
int _ab;
int a30;
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.
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 Ternary or Conditional Operator
o Misc Operator
a + b;
Here, the + operator is used to add two variables a and b. Similarly there are various other
arithmetic operators in C++.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
// increment operator
++num; // 6
Here, the code ++num; increases the value of num by 1.
Example 2: Increment and Decrement Operators
// Working of increment and decrement operators
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 100, result_a, result_b;
return 0;
}
Output
result_a = 11
result_b = 99
2. C++ Assignment Operators
In C++, assignment operators are used to assign values to variables. For example,
// assign 5 to a
a = 5;
= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;
int main() {
int a, b;
// 2 is assigned to a
a = 2;
// 7 is assigned to b
b = 7;
return 0;
}
Output
a=2
b=7
After a += b;
a=9
3. C++ Relational Operators
A relational operator is used to check the relationship between two operands. For example,
int main() {
int a, b;
a = 3;
b = 5;
bool result;
return 0;
}
Output
3 == 5 is 0
3 != 5 is 1
3 > 5 is 0
3 < 5 is 1
3 >= 5 is 0
3 <= 5 is 1
4. C++ Logical Operators
Logical operators are used to check whether an expression is true or false. If the expression
is true, it returns 1 whereas if the expression is false, it returns 0.
Operator Example Meaning
Logical AND.
expression1 &&
&& True only if all the operands
expression2
are true.
Logical OR.
expression1 ||
|| True if at least one of the
expression2
operands is true.
Logical NOT.
! !expression True only if the operand is
false.
In C++, logical operators are commonly used in decision making. To further understand the
logical operators, let's see the following examples,
Suppose,
a=5
b=8
Then,
(a > 3) && (b > 5) evaluates to true
(a > 3) && (b < 5) evaluates to false
(a > 3) || (b > 5) evaluates to true
(a > 3) || (b < 5) evaluates to true
(a < 3) || (b < 5) evaluates to false
!(a < 3) evaluates to true
!(a > 3) evaluates to false
Example 5: Logical Operators
#include <iostream>
using namespace std;
int main() {
bool result;
result = (3 != 5) && (3 < 5); // true
cout << "(3 != 5) && (3 < 5) is " << result << endl;
result = (3 == 5) && (3 < 5); // false
cout << "(3 == 5) && (3 < 5) is " << result << endl;
result = (3 == 5) && (3 > 5); // false
cout << "(3 == 5) && (3 > 5) is " << result << endl;
result = (3 != 5) || (3 < 5); // true
cout << "(3 != 5) || (3 < 5) is " << result << endl;
result = (3 != 5) || (3 > 5); // true
cout << "(3 != 5) || (3 > 5) is " << result << endl;
result = (3 == 5) || (3 > 5); // false
cout << "(3 == 5) || (3 > 5) is " << result << endl;
result = !(5 == 2); // true
cout << "!(5 == 2) is " << result << endl;
result = !(5 == 5); // false
cout << "!(5 == 5) is " << result << endl;
return 0;}
Output
(3 != 5) && (3 < 5) is 1
(3 == 5) && (3 < 5) is 0
(3 == 5) && (3 > 5) is 0
(3 != 5) || (3 < 5) is 1
(3 != 5) || (3 > 5) is 1
(3 == 5) || (3 > 5) is 0
!(5 == 2) is 1
!(5 == 5) is 0
Explanation of logical operator program
(3 != 5) && (3 < 5) evaluates to 1 because both operands (3 != 5) and (3 < 5) are 1 (true).
(3 == 5) && (3 < 5) evaluates to 0 because the operand (3 == 5) is 0 (false).
(3 == 5) && (3 > 5) evaluates to 0 because both operands (3 == 5) and (3 > 5) are 0 (false).
(3 != 5) || (3 < 5) evaluates to 1 because both operands (3 != 5) and (3 < 5) are 1 (true).
(3 != 5) || (3 > 5) evaluates to 1 because the operand (3 != 5) is 1 (true).
(3 == 5) || (3 > 5) evaluates to 0 because both operands (3 == 5) and (3 > 5) are 0 (false).
!(5 == 2) evaluates to 1 because the operand (5 == 2) is 0 (false).
!(5 == 5) evaluates to 0 because the operand (5 == 5) is 1 (true).
| Binary OR
^ Binary XOR
~ Binary One's Complement
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
o Defined data types
Some naming rules are common in both C and C++. They are as follows:
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.
Valid Identifiers
Result
Test2
_sum
power
Invalid Identifiers
#include <iostream>
using namespace std;
int main()
{
int a;
int A;
cout<<"Enter the values of 'a' and 'A'";
cin>>a;
cin>>A;
cout<<"\nThe values that you have entered are : "<<a<<" , "<<A;
return 0;
}
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.
Output
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
if(condition){
//code to be executed
}
C++ If Example
#include <iostream>
using namespace std;
int main () {
int num = 10;
if (num % 2 == 0)
{
cout<<"It is even number";
}
return 0;
}
Output:/p>
It is even number
The C++ if-else statement also tests the condition. It executes if block if condition is true
otherwise else block is executed.
if(condition){
//code if condition is true
}else{
//code if condition is false
}
C++ If-else Example
#include <iostream>
using namespace std;
int main () {
int num = 11;
if (num % 2 == 0)
{
cout<<"It is even number";
}
else
{
cout<<"It is odd number";
}
return 0;
}
Output:
It is odd number
Output:
Enter a number:11
It is odd number
Output:
Enter a number:12
It is even number
The C++ if-else-if ladder statement executes one condition from multiple statements.
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Output:
Output:
C++ switch
The C++ switch statement executes one statement from multiple conditions. It is like if-else-if
ladder statement in C++.
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
//code to be executed if all cases are not matched;
break;
}
Output:
Enter a number:
10
It is 10
Output:
Enter a number:
55
Not 10, 20 or 30
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
2
3
4
5
6
7
8
9
10
In C++, we can use for loop inside another for loop, it is known as nested for loop. The inner loop
is executed fully when outer loop is executed one time. So if outer loop and inner loop are
executed 4 times, inner loop will be executed 4 times for each outer loop i.e. total 16 times.
#include <iostream>
using namespace std;
int main () {
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
cout<<i<<" "<<j<<"\n";
}
}
}
Output:
11
12
13
21
22
23
31
32
33
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.
while(condition){
//code to be executed
}
Flowchart:
#include <iostream>
using namespace std;
int main() {
int i=1;
while(i<=10)
{
cout<<i <<"\n";
i++;
}
}
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.
#include <iostream>
using namespace std;
int main () {
int i=1;
while(i<=3)
{
int j = 1;
while (j <= 3)
{
cout<<i<<" "<<j<<"\n";
j++;
}
i++;
}
}
Output:
11
12
13
21
22
23
31
32
33
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.
do{
//code to be executed
}while(condition);
Flowchart:
C++ do-while Loop Example
Let's see a simple example of C++ do-while loop to print the table of 1.
#include <iostream>
using namespace std;
int main() {
int i = 1;
do{
cout<<i<<"\n";
i++;
} while (i <= 10) ;
}
Output:
1
2
3
4
5
6
7
8
9
10
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.
#include <iostream>
using namespace std;
int main() {
int i = 1;
do{
int j = 1;
do{
cout<<i<<"\n";
j++;
} while (j <= 3) ;
i++;
} while (i <= 3) ;
}
Output:
11
12
13
21
22
23
31
32
33
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.
jump-statement;
break;
Flowchart:
C++ Break Statement Example
Let's see a simple example of C++ break statement which is used inside the loop.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;
}
cout<<i<<"\n";
} }
The C++ break statement breaks inner loop only if you use break statement inside the inner loop.
#include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break;
}
cout<<i<<" "<<j<<"\n";
}
}
}
Output:
11
12
13
21
31
32
33
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;
continue;
C++ Continue Statement Example
#include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=10;i++){
if(i==5){
continue;
}
cout<<i<<"\n";
} }
Output:
1
2
3
4
6
7
8
9
10
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.
#include <iostream>
using namespace std;
int main()
{
ineligible:
cout<<"You are not eligible to vote!\n";
cout<<"Enter your age:\n";
int age;
cin>>age;
if (age < 18){
goto ineligible;
}
else
{
cout<<"You are eligible to vote!";
}}
C++ Functions
The function in C++ language is also known as procedure or subroutine in other programming
languages.
To perform any task, we can create function. A function can be called many times. It provides
modularity and code reusability.
Advantage of functions in C
1) Code Reusability
By creating functions in C++, you can call it many times. So we don't need to write the
same code again and again.
2) Code optimization
It makes the code optimized; we don't need to write much code.
Suppose, you have to check 3 numbers (531, 883 and 781) whether it is prime number or
not. Without using function, you need to write the prime number logic 3 times. So, there is
repetition of code.
But if you use functions, you need to write the logic only once and you can reuse it several
times.
Create a Function
C++ provides some pre-defined functions, such as main(), which is used to execute code. But you
can also create your own functions to perform certain actions.
To create (often referred to as declare) a function, specify the name of the function, followed by
parentheses ():
Declaration of a function
void means that the function does not have a return value.
inside the function (the body), add code that defines what the function should do
Call a Function
Declared functions are not executed immediately. They are "saved for later use", and will
be executed later, when they are called.
To call a function, write the function's name followed by two parentheses () and a
semicolon ;
In the following example, myFunction() is used to print a text (the action), when it is
called:
Example
Inside main, call myFunction():
// Create a function
void myFunction()
{
cout << "Function call";
}
int main() {
myFunction(); // call the function
//myFunction();
//myFunction();
return 0;
}
Function Declaration and Definition
Declaration: the function's name, return type, and parameters (if any)
Definition: the body of the function (code to be executed)
#include <iostream>
using namespace std;
// Function declaration
void myFunction();
// Function definition
void myFunction()
{
cout << "I just got executed!";
}
Information can be passed to functions as a parameter. Parameters act as variables inside the
function.
Parameters are specified after the function name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma:
Syntax
void functionName(parameter1, parameter2, parameter3)
{
// code to be executed
}
Example
void myFunction(string fname)
{
cout << fname << " welcome\n";
}
int main() {
myFunction("Nithish");
myFunction("Kumar");
myFunction("Raja");
return 0;
}
You can also use a default parameter value, by using the equals sign (=).
If we call the function without an argument, it uses the default value ("KRCE"):
Example
{
cout << country << "\n";
}
int main() {
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
}
Multiple Parameters
Inside the function, you can add as many parameters as you want:
Example
int main()
{
myFunction("Rose", 3);
myFunction("Jenny", 14);
myFunction("Deepa", 30);
return 0;
}
Return Values
If you want the function to return a value, you can use a data type (such as int, string, etc.) instead
of void, and use the return keyword inside the function:
Example 1
int myFunction(int x)
{
return 5 + x;
}
int main()
{
cout << myFunction(3);
return 0;
}
Example 2
int myFunction(int x, int y)
{
return x + y;
}
int main()
{
cout << myFunction(5, 3);
return 0;
}
Pass By Reference
In the examples, we used normal variables when we passed parameters to a function. You can also
pass a reference to the function. This can be useful when you need to change the value of the
arguments:
Example
void swapNums(int &x, int &y)
{
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
// Call the function, which will change the values of firstNum and secondNum
swapNums(firstNum, secondNum);
return 0;
}
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
2. Multidimensional Array
Example
#include <iostream>
using namespace std;
int main()
{
int arr[5]={10, 20, 30, 40, 50}; //creating and initializing array
//traversing array
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
}
C++ Multidimensional Array Example
Let's see a simple example of multidimensional array in C++ which declares, initializes and
traverse two dimensional arrays.
#include <iostream>
using namespace std;
int main()
{
int test[3][3]; //declaration of 2D array
test[0][0]=5; //initialization
test[0][1]=10;
test[1][1]=15;
test[1][2]=20;
test[2][0]=30;
test[2][2]=10;
//traversal
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
cout<< test[i][j]<<" ";
}
cout<<"\n"; //new line at each row
}
return 0;
}
Output:
5 10 0
0 15 20
30 0 10
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.
Declaring a pointer
#include <iostream>
using namespace std;
int main()
{
int ∗ p;
int number=30;
p=&number;//stores the address of number variable
cout<<"Address of number variable is:"<<&number<<endl;
cout<<"Address of p variable is:"<<p<<endl;
cout<<"Value of p variable is:"<<*p<<endl;
return 0;
}
Output:
A member function of a class is a function that has its definition or its prototype within the class
definition like any other variable. If the member function is defined inside the class definition it
can be defined directly, but if it is defined outside the class, then we have to use the scope
resolution :: operator along with class name along with function name.
Syntax
class className
{
returnType MemberFunction(arguments)
{
//function body
}
....
};
syntax
class className
{
returnType MemberFunction(arguments);
....
};
1. Simple functions
2. Static functions
3. Const functions
4. Inline functions
5. Friend functions
1) Simple functions:
These are the basic member function, which doesn’t have any special keyword like static etc as
a prefix.
return_type functionName(parameter_list)
{
function body;
}
2) Static functions:
Static is a keyword which can be used with data members as well as the member functions. A
function is made static by using the static keyword with the function name. These functions
work for the class as whole rather than for a particular object of a class. It can be called using
the object and the direct member access operator. But, its more typical to call a static member
function by itself, using class name and scope resolution :: operator.
A static member function is a special member function, which is used to access only static
data members, any other normal data member cannot be accessed through static member
function. Just like static data member, static member function is also a class function; it is not
associated with any class object.
We can access a static member function with class name, by using following syntax:
class_name:: function_name(perameter);
#include <iostream>
class Demo
{
private:
//static data members
static int X;
static int Y;
public:
//static member function
static void Print()
{
cout <<"Value of X: " << X << endl;
cout <<"Value of Y: " << Y << endl;
}
};
int main()
{
Demo OB;
//accessing class name with object name
cout<<"Printing through object name:"<<endl;
OB.Print();
return 0;
}
3) Const functions:
Declaring a member function with the const keyword specifies that the function is a "read-only"
function that does not modify the object for which it is called. A constant member function
cannot modify any non-static data members or call any member functions that aren't
constant.To declare a constant member function, place the const keyword after the closing
parenthesis of the argument list. The const keyword is required in both the declaration and the
definition.
#include <iostream>
using namespace std;
int main() {
const int myNum = 15;
myNum=20;
cout << myNum;
return 0;
}
#include<iostream>
using namespace std;
class Test {
int value;
public:
Test(int v = 0)
{
value = v;
}
int main() {
Test t(20);
cout<<t.getValue();
return 0;
}
If make a function as inline, then the compiler replaces the function calling location with the
definition of the inline function at compile time.
Any changes made to an inline function will require the inline function to be recompiled again
because the compiler would need to replace all the code with a new code; otherwise, it will
execute the old functionality.
Normally, a function call transfers the control from the calling program to the called function.
This process of jumping to the function, saving registers, passing a value to the argument, and
returning the value to the calling function takes extra time and memory.
An inline function is a function that is expanded inline when it is invoked, thus saving time. The
compiler replaces the function call with the corresponding function code, which reduces the
overhead of function calls.
When an inline function is called, the compiler replaces all the calling statements with the
function definition at run-time. Every time an inline function is called, the compiler generates a
copy of the function’s code, in place, to avoid the function call.
Example Program
#include <iostream>
using namespace std;
#include<iostream>
using namespace std;
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
cout<<"Addition of 'a' and 'b' is:"<<return(2+3);
return 0;
}
The main use of the inline function in C++ is to save memory space. Whenever the function is
called, then it takes a lot of time to execute the tasks, such as moving to the calling function. If the
length of the function is small, then the substantial amount of execution time is spent in such
overheads, and sometimes time taken required for moving to the calling function will be greater
than the time taken required to execute that function.
5) Friend function:
If a function is defined as a friend function then, the private and protected data of a class can be
accessed using the function. The compiler knows a given function is a friend function by the use
of the keyword friend. For accessing the data, the declaration of a friend function should be
made inside the body of the class starting with keyword friend.
1) A program can have several classes and they can have member functions with the same
name, Ambiguity is resolved using the scope resolution operator (::)
2) Private members of a class can be accessed by all the members of the class, whereas non-
member functions are not allowed to access.
3) Member functions of the same class can access all other members of their own class without
the use of dot operator.
4) Member functions defined as public act as an interface between the service provider and the
service seeker.
5) Member functions can take default arguments as well.
class Distance {
private:
int meter;
public:
Distance(): meter(0){ }
friend int func(Distance); //friend function
};
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
#include <iostream>
using namespace std;
class Employee
{
public:
int id;
string name;
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, "Kumar", 50000); //creating an object of Employee
Employee e2=Employee(102, "Nithish", 55000);
e1.display();
e2.display();
return 0;
}
Output
101 Kumar 50000
102 Nithish 55000
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 (~).
Destructor rules
1) Name should begin with tilde sign(~) and must match class name.
2) There cannot be more than one destructor in a class.
3) Unlike constructors that can have parameters, destructors do not allow any parameter.
4) They do not have any return type, just like constructors.
5) When you do not specify any destructor in a class, compiler generates a default destructor and
inserts it into your code.
#include <iostream>
using namespace std;
class Employee
{
int num;
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked 1"<<endl;
}
Employee(int a)
{
num=a;
cout<<a<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2(10);
return 0;
}
Object as a data type
These are also referred to as Non-primitive or Reference Data Type. They are so-called because
they refer to any particular objects. Unlike the primitive data types, the non-primitive ones are
created by the users in C++. Examples include arrays, strings, classes, interfaces etc. When the
reference variables will be stored, the variable will be stored in the stack and the original object
will be stored in the heap. In Object data type although two copies will be created they both will
point to the same variable in the heap, hence changes made to any variable will reflect the change
in both the variables.
Example 1
#include <iostream>
#include <string>
using namespace std;
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
int main() {
// Create an object of MyClass
MyClass obj;
// Access attributes and set values
obj.myNum = 15;
obj.myString = "Some text";
// Print values
cout <<obj.myNum << "\n";
cout << obj.myString;
return 0;
}
Example 2
#include <iostream>
#include <string>
using namespace std;
class Distance
{
private:
int feet;
float inches;
public:
void setdist(int ft,float in)
{
feet=ft;
inches=in;
}
void getdist()
{
cout<<"\n Enter feet: ";
cin>>feet;
cout<<"\n Enter inches: ";
cin>>inches;
}
void showdist()
{
cout<<feet;
cout<<inches;
}
};
int main()
{
Distance dist1,dist2;
dist1.setdist(11,6.25);
dist2.getdist();
}
Objects as function arguments
The objects of a class can be passed as arguments to member functions as well as nonmember
functions either by value or by reference. When an object is passed by value, a copy of the actual
object is created inside the function. This copy is destroyed when the function terminates.
Moreover, any changes made to the copy of the object inside the function are not reflected in the
actual object. On the other hand, in pass by reference, only a reference to that object (not the
entire object) is passed to the function. Thus, the changes made to the object within the function
are also reflected in the actual object.
Whenever an object of a class is passed to a member function of the same class, its data members
can be accessed inside the function using the object name and the dot operator. However, the data
members of the calling object can be directly accessed inside the function without using the
object name and the dot operator.
#include <iostream>
using namespace std;
class Demo
{
private:
int a;
public:
void set(int x)
{
a = x;
}
void print()
{
cout<<"Value of A : "<<a<<endl;
}
};
int main()
{
//object declarations
Demo d1;
Demo d2;
Demo d3;
return 0;
}
Output
Value of A : 10
Value of A : 20
Value of A : 30
Above example demonstrate the use of object as a parameter. We are passing d1 and d2 objects as
arguments to the sum member function and adding the value of data members a of both objects
and assigning to the current object’s (that will call the function, which is d3) data member a.
A structure is a grouping of variables of various data types referenced by the same name. A
structure declaration serves as a template for creating an instance of the structure.
Syntax:
Struct Structurename
{
Struct_member1;
Struct_member2;
Struct_member3;
.
.
.
Struct_memberN;
};
The "struct" keyword indicates to the compiler that a structure has been declared.
The "structurename" defines the name of the structure. Since the structure declaration is treated
as a statement, so it is often ended by a semicolon.
A class in C++ is similar to a C structure in that it consists of a list of data members and a set of
operations performed on the class. In other words, a class is the building block of Object-
Oriented programming. It is a user-defined object type with its own set of data members and
member functions that can be accessed and used by creating a class instance. A C++ class is
similar to an object's blueprint.
Syntax:
The structure and the class are syntactically similar. The syntax of class in C++ is as follows:
class class_name
{
// private data members and member functions.
Access specifier;
Data member;
Member functions (member list){ . . }
};
In this syntax, the class is a keyword to indicate the compiler that a class has been declared. OOP's
main function is data hiding, which is achieved by having three access specifiers: "public",
"private", and "safe". If no access specifier is specified in the class when declaring data
members or member functions, they are all considered private by default.
The public access specifier allows others to access program functions or data. A member of that
class may reach only the class's private members. During inheritance, the safe access specifier is
used. If the access specifier is declared, it cannot be changed again in the program.
Here, we are going to discuss a head-to-head comparison between the structure and class. Some of
them are as follows:
Usage It is used for smaller amounts of It is used for a huge amount of data.
data.
Requires It may have only parameterized It may have all the types of
constructor and constructor. constructors and destructors.
destructor
Similarities
o Both class and structure may declare any of their members private.
o Both class and structure support inheritance mechanisms.
o Both class and structure are syntactically identical in C++.
o A class's or structure's name may be used as a stand-alone type.
#include <iostream>
using namespace std;
struct st
{
void sum()
{
cout<<"new"<<endl;
}
};
class Demo
{
public:
void fun()
{
cout<<"welcome"<<endl;
}
};
int main()
{
Demo d;
st s;
d.fun();
s.sum();
}
Static members exist as members of the class rather than as an instance in each object of the
class. So, this keyword is not available in a static member function. Such functions may access
only static data members. There is a single instance of each static data member for the entire
class, which should be initialized, usually in the source file that implements the class member
functions. Because the member is initialized outside the class definition, we must use fully
qualified name when we initialize it:
class_name::static_member_name = value;
#include <iostream>
class Box
{
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
public:
static int objectCount;
double sum=0;
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0)
{
cout<< sum<<"\n";
}
};
int main()
{
return 0;
}
Output
Constructor called.
Constructor called.
5.94
Total objects: 2
The member functions and member function arguments, the objects of a class can also be declared
as const. an object declared as const cannot be modified and hence, can invoke only const
member functions as these functions ensure not to modify the object.
A const object can be created by prefixing the const keyword to the object declaration. Any
attempt to change the data member of const objects results in a compile-time error.
Syntax:
const Class_Name Object_name;
When a function is declared as const, it can be called on any type of object, const object as
well as non-const objects.
Whenever an object is declared as const, it needs to be initialized at the time of declaration.
however, the object initialization while declaring is possible only with the help of
constructors.
A function becomes const when the const keyword is used in the function’s declaration. The idea
of const functions is not to allow them to modify the object on which they are called. It is
recommended the practice to make as many functions const as possible so that accidental changes
to objects are avoided.
class Test
{
int value;
public:
Test(int v = 0)
{
value = v;
}
int main()
{
const Test t(20);
cout << t.getValue();
return 0;
}
Output
20
Inline function in C++
If make a function as inline, then the compiler replaces the function calling location with the
definition of the inline function at compile time.
Any changes made to an inline function will require the inline function to be recompiled again
because the compiler would need to replace all the code with a new code; otherwise, it will
execute the old functionality.
Normally, a function call transfers the control from the calling program to the called function.
This process of jumping to the function, saving registers, passing a value to the argument, and
returning the value to the calling function takes extra time and memory.
An inline function is a function that is expanded inline when it is invoked, thus saving time. The
compiler replaces the function call with the corresponding function code, which reduces the
overhead of function calls.
When an inline function is called, the compiler replaces all the calling statements with the
function definition at run-time. Every time an inline function is called, the compiler generates a
copy of the function’s code, in place, to avoid the function call.
Example Program
#include <iostream>
using namespace std;
#include<iostream>
using namespace std;
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
cout<<"Addition of 'a' and 'b' is:"<<return(2+3);
return 0;
}
The main use of the inline function in C++ is to save memory space. Whenever the function is
called, then it takes a lot of time to execute the tasks, such as moving to the calling function. If the
length of the function is small, then the substantial amount of execution time is spent in such
overheads, and sometimes time taken required for moving to the calling function will be greater
than the time taken required to execute that function.