CPP Notes
CPP Notes
Getting Started
A computer cannot understand our language that we use in our day to day
conversations, and likewise, we cannot understand the binary language that the
computer uses to do it‟s tasks. It is therefore necessary for us to write
instructions in some specially defined language like C++ which is like natural
language and after converting with the help of compiler the computer can
understand it.
C++ Compiler
A C++ compiler is itself a computer program which‟s only job is to convert the
C++ program from our form to a form the computer can read and execute. The
original C++ program is called the “source code”, and the resulting compiled
code produced by the compiler is usually called an “object file”.
After compilation stage object files are combined with predefined libraries by a
linker, sometimes called a binder, to produce the final complete file that can be
executed by the computer. A library is a collection of pre-compiled “object code”
that provides operations that are done repeatedly by many computer programs.
Integrated Development Environment
Above Figure illustrates the process of translating a C++ source file into an
executable file. You can perform entire process of invoking the preprocessor,
compiler, and linker with a single action by using Integrated Development
environment. These environments consist of a text editor, compiler, debugger,
and other utilities integrated into a package with a single set of menus.
Preprocessing, compiling, linking, and even executing a program is done by
selecting a single item from a menu.
Following Figure shows a screen from the Microsoft Visual C++ IDE.
Read Creating and running a program using Microsoft Visual C++ Express
Edition
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!";
return 0;
}
When the above program is compiled, linked and executed, the following
output is displayed on the VDU screen.
Hello World!
Comments
First three lines of the above program are comments and are ignored by the
compiler. Comments are included in a program to make it more readable. If a
comment is short and can be accommodated in a single line, then it is started
with double slash sequence in the first line of the program. However, if there
are multiple lines in a comment, it is enclosed between the two symbols /* and
*/
#include <iostream>
The line in the above program that start with # symbol are called directives and
are instructions to the compiler. The word include with '#' tells the compiler to
include the file iostream into the file of the above program. File iostream is a
header file needed for input/ output requirements of the program. Therefore,
this file has been included at the top of the program.
using namespace std;
All the elements of the standard C++ library are declared within std. This line is
very frequent in C++ programs that use the standard library.
int main ( )
The word main is a function name. The brackets ( ) with main tells that main ( )
is a function. The word int before main ( ) indicates that integer value is being
returned by the function main (). When program is loaded in the memory, the
control is handed over to function main ( ) and it is the first function to be
executed.
A C++ program starts with function called main(). The body of the function is
enclosed between curly braces. The program statements are written within the
brackets. Each statement must end by a semicolon, without which an error
message in generated.
cout<<"Hello World!";
This statement prints our "Hello World!" message on the screen. cout
understands that anything sent to it via the << operator should be printed on
the screen.
return 0;
#include <iostream>
using namespace std;
int main()
{
cout << "Welcome\nto\nC++";
return 0;
}
Output:
Welcome
to
C++
The characters print exactly as they appear between the double quotes.
However, if we type \n, the characters \n are not printed on the screen. The
backslash (\) is called an escape character. It indicates that a "special"
character is to be output. When a backslash is encountered in a string of
characters, the next character is combined with the backslash to form an
escape sequence. The escape sequence \n means newline. It causes the
cursor to move to the beginning of the next line on the screen.
\n Newline
\t Horizontal tab
\a Bell (beep)
\\ Backslash
Location of the computer memory which is used to store data and is given a
symbolic name for reference is known as variable. We need three variables, two
for storing input and third for storing result. Before a variable is used in a
program, we must declare it. This activity enables the compiler to make
available the appropriate type of location in the memory.
You can declare more than one variable of same type in a single statement like :
int x, y, z;
STEP 4 : Now, add these two numbers together and store the result of the
addition in third variable
z = x + y;
int main()
{
//declare variables of integer type
int x;
int y;
int z;
return 0;
}
Output : The sum is 35
Identifiers
Symbolic names can be used in C++ for various data items used by a
programmer in his program. A symbolic name is generally known as an
identifier. The identifier is a sequence of characters taken from C++ character
set. In previous program x, y and z are identifiers of variables. The rule for the
formation of an identifier are:
Keywords
There are some reserved words in C++ which have predefined meaning to
compiler called keywords. These words may not be used as identifiers. Some
commonly used Keywords are given below:
Digits 0-9
Space + - * / ^ \ () [] {} = !=
Special
<> „ “ $ , ; : % ! & ? _ # <= >=
Characters
@
Tokens
1. Keywords
These are some reserved words in C++ which have predefined meaning to
compiler called keywords. It is discussed in previous section.
2. Identifiers
Symbolic names can be used in C++ for various data items used by a
programmer in his program. A symbolic name is generally known as an
identifier. The identifier is a sequence of characters taken from C++ character
set. The rule for the formation of an identifier are:
3. Literals
Literals (often referred to as constants) are data items that never change their
value during the execution of the program. The following types of literals are
available in C++.
Integer-Constants
Character-constants
Floating-constants
Strings-constants
Integer Constants
Integer constants are whole number without any fractional part. C++ allows
three types of integer constants.
Decimal integer constants : It consists of sequence of digits and should not
begin with 0 (zero). For example 124, - 179, +108.
Octal integer constants: It consists of sequence of digits starting with 0
(zero). For example. 014, 012.
Hexadecimal integer constant: It consists of sequence of digits preceded by
ox or OX.
Character constants
A character constant in C++ must contain one or more characters and must be
enclosed in single quotation marks. For example 'A', '9', etc. C++ allows
nongraphic characters which cannot be typed directly from keyboard, e.g.,
backspace, tab, carriage return etc. These characters can be represented by
using an escape sequence. An escape sequence represents a single character.
Floating constants
They are also called real constants. They are numbers having fractional parts.
They may be written in fractional form or exponent form. A real constant in
fractional form consists of signed or unsigned digits including a decimal point
between digits. For example 3.0, -17.0, -0.627 etc.
String Literals
4. Punctuators
The following characters are used as punctuators in C++.
5. Operators
Operators are special symbols used for specific purposes. C++ provides six
types of operators. Arithmetical operators, Relational operators, Logical
operators, Unary operators, Assignment operators, Conditional operators,
Comma operator
CPP Programming
Operators
Operators are special symbols used for specific purposes. C++ provides six
types of operators.
Arithmetical operators, Relational operators, Logical operators, Unary operators,
Assignment operators, Conditional operators, Comma operator
Arithmetical operators
Arithmetical operators +, -, *, /, and % are used to performs an arithmetic
(numeric) operation. You can use the operators +, -, *, and / with both integral
and floating-point data types. Modulus or remainder % operator is used only
with the integral data type.
Operators that have two operands are called binary operators.
Relational operators
The relational operators are used to test the relation between two values. All
relational operators are binary operators and therefore require two operands. A
relational expression returns zero when the relation is false and a non-zero
when it is true. The following table shows the relational operators.
== Equal to
!= Not equal to
Logical operators
The logical operators are used to combine one or more relational expression.
The logical operators are
Operators Meaning
|| OR
&& AND
! NOT
Unary operators
C++ provides two unary operators for which only one variable is required.
For Example
a = - 50;
a = + 50;
Here plus sign (+) and minus sign (-) are unary because they are not used
between two variables.
Assignment operator
The assignment operator '=' is used for assigning a variable to a value. This
operator takes the expression on its right-hand-side and places it into the
variable on its left-hand-side. For example:
m = 5;
The operator takes the expression on the right, 5, and stores it in the variable
on the left, m.
x = y = z = 32;
This code stores the value 32 in each of the three variables x, y, and z.
in addition to standard assignment operator shown above, C++ also support
compound assignment operators.
+= A+=2 A=A+2
-= A-=2 A=A-2
%= A%=2 A=A%2
/= A/ = 2 A=A/2
*= A*=2 A=A*2
The condition evaluates to false, therefore biggets the value from b and it
becomes 6.
Would first assign the value of a to i, and then assign value of b to variable i.
So, at the end, variable i would contain the value 2.
the sizeof operator determines the amount of memory required for an object at
compile time rather than at run time.
The order of Precedence
The order in which the Arithmetic operators (+,-,*,/,%) are used in a. given
expression is called the order of precedence. The following table shows the
order of precedence.
Order Operators
First ()
Second *, /, %
Third +, -
+, -
Lowest
<, <=, >, >=
==,!=
&&
?:
Comma operator
CPP Programming
Data Handling
Some commonly used data types are summarized in table along with
description.
Type Description
The exact sizes and ranges of values for the fundamental types are
implementation dependent. The header files <climits> (for the integral types)
and <cfloat> (for the floating-point types) specify the ranges of values
supported on your system.
int main ()
{
string mystring = "This is a string";
cout << mystring;
return 0;
}
Variable Initialization
Variable is a location in the computer memory which can store data and is given
a symbolic name for easy reference. The variables can be used to hold different
values at different times during the execution of a program.
Declaration of a variable
Before a variable is used in a program, we must declare it. This activity enables
the compiler to make available the appropriate type of location in the memory.
float total;
You can declare more than one variable of same type in a single single
statement
int x, y;
Initialization of variable
Constants
A variable which does not change its value during execution of a program is
known as a constant variable. Any attempt to change the value of a constant
will result in an error message. A constant in C++ can be of any of the basic
data types, const qualifier can be used to declare constant as shown below:
const float PI = 3.1415;
The above declaration means that PI is a constant of float types having a value
3.1415.
Examples of valid constant declarations are:
const int RATE = 50;
const float PI = 3.1415;
const char CH = 'A';
Type Conversion
The process in which one pre-defined type of expression is converted into
another type is called conversion. There are two types of conversion in C++.
1. Implicit conversion
2. Explicit conversion
Implicit conversion
Data type can be mixed in the expression. For example
double a;
int b = 5;
float c = 8.5;
a = b * c;
When two operands of different type are encountered in the same expression,
the lower type variable is converted to the higher type variable. The following
table shows the order of data types.
order
Data type
long double
(highest)
double
float
long To
int
char (lowest)
The int value of b is converted to type float and stored in a temporary variable
before being multiplied by the float variable c. The result is then converted to
double so that it can be assigned to the double variable a.
Explicit conversion
It is also called type casting. It temporarily changes a variable data type from
its declared data type to a new one. It may be noted here that type casting can
only be done on the right hand side the assignment statement.
totalPay = static_cast<double>(salary) + bonus;
Initially variable salary is defined as float but for the above calculation it is
first converted to double data type and then added to the variable bonus.
CPP Programming
Input/Output (I/O)
The standard C++ library includes the header file iostream, which can be used
to feed new data into the computer or obtain output on an output device such
as: VDU, printer etc. The following C++ stream objects can be used for the
input/output purpose.
cout object
cout is used to print message on screen in conjunction with the insertion
operator <<
cout << "Hello World"; // prints Hello world on screen
cout << 250; // prints number 250 on screen
cout << sum; // prints the content of variable sum on screen
If we assume the area variable to contain the value 24 the output of the
previous statement would be:
Area of rectangle is 24 square meter
cin object
cin can be used to input a value entered by the user from the keyboard.
However, the extraction operator >> is also required to get the typed value
from cin and store it in the memory location.
Let us consider the following program segment:
int marks;
cin >> marks;
In the above segment, the user has defined a variable marks of integer type in
the first statement and in the second statement he is trying to read a value
from the keyboard.
int main ()
{
int length;
int breadth;
int area;
Output :
You can also use cin to request more than one input from the user:
cin >> length >> breadth;
is equivalent to:
cin >> length;
cin >> breadth;
cin and strings
We can use cin to get strings with the extraction operator (>>) as we do with
fundamental data type variables:
cin >> mystring;
However, cin extraction stops reading as soon as if finds any blank space
character, so in this case we will be able to get just one word for each
extraction.
for example if we want to get a sentence from the user, this extraction
operation would not be useful. In order to get entire lines, we can use the
function getline, which is the more recommendable way to get user input with
cin:
int main ()
{
string name;
cout << "Enter your name";
getline (cin, name);
cout << "Hello " << name << "!\n";
return 0;
}
Output
Flow of Control
Statements
Statements are the instructions given to the computer to perform any kind of
action. Action may be in the form of data movement, decision making etc.
Statements form the smallest executable unit within a C++ program.
Statements are always terminated by semicolon.
Compound Statement
Null Statement
Writing only a semicolon indicates a null statement. Thus ';' is a null or empty
statement. This is quite useful when the syntax of the language needs to specify
a statement but the logic of the program does not need any statement. This
statement is generally used in for and while looping statements.
Conditional Statements
if statement
if else statement
nested if statement
switch statement
if statement
From the flowchart it is clear that if the if condition is true, statement is executed;
otherwise it is skipped. The statement may either be a single or compound statement.
if else statement
syntax of the if - else statement
if (condition)
statement1;
else
statement2;
From the above flowchart it is clear that the given condition is evaluated first. If the
condition is true, statement1 is executed. If the condition is false, statement2 is
executed. It should be kept in mind that statement and statement2 can be single or
compound statement.
if (x == 100) if (x == 100)
cout << "x is 100"; cout << "x is 100";
else
cout << "x is not 100";
Nested if statement
The if block may be nested in another if or else block. This is called nesting of if
or else block.
if(condition 1)
statement 1;
else if (condition 2)
statement2;
else
statement3;
if-else-if example
if(percentage>=60)
cout<<"Ist division";
else if(percentage>=50)
cout<<"IInd division";
else if(percentage>=40)
cout<<"IIIrd division";
else
cout<<"Fail" ;
switch statement
The if and if-else statements permit two way branching whereas switch
statement permits multiple branching. The syntax of switch statement is:
switch (var / expression)
{
case constant1 : statement 1;
break;
case constant2 : statement2;
break;
.
.
default: statement3;
break;
}
Flow of Control
Looping statement
while loop
do-while loop
for loop
While loop
The flow diagram indicates that a condition is first evaluated. If the condition is
true, the loop body is executed and the condition is re-evaluated. Hence, the loop
body is executed repeatedly as long as the condition remains true. As soon as the
condition becomes false, it comes out of the loop and goes to the statement next to
the „while‟ loop.
do-while loop
Syntax of do-while loop
do
{
statements;
} while (condition);
Note : That the loop body is always executed at least once. One important
difference between the while loop and the do-while loop the relative ordering of
the conditional test and loop body execution. In the while loop, the loop
repetition test is performed before each execution the loop body; the loop body
is not executed at all if the initial test fail. In the do-while loop, the loop
termination test is Performed after each execution of the loop body. hence, the
loop body is always executed least once.
for loop
It is a count controlled loop in the sense that the program knows in advance
how many times the loop is to be executed.
The flow diagram indicates that in for loop three operations take place:
Operation (i) is used to initialize the value. On the other hand, operation (ii) is
used to test whether the condition is true or false. If the condition is true, the
program executes the body of the loop and then the value of loop control
variable is updated. Again it checks the condition and so on. If the condition is
false, it gets out of the loop.
Jump Statements
goto statement
break statement
continue statement
The C++ Standard Library provides a rich collection of functions for performing
common mathematical calculations, string manipulations, character manipulations,
input/output, error checking and many other useful operations. This makes the
programmer's job easier, because these functions provide many of the capabilities
programmers need. The C++ Standard Library functions are provided as part of the
C++ programming environment.
Header file names ending in .h are "old-style" header files that have been
superseded by the C++ Standard Library header files.
C++ Standard
Library header
file Explanation
<iostream> Contains function prototypes for the C++ standard input and
standard output functions. This header file replaces header file
<iostream.h>.
<cctype> Contains function prototypes for functions that test characters for
certain properties (such as whether the character is a digit or a
punctuation), and function prototypes for functions that can be
used to convert lowercase letters to uppercase letters and vice
versa. This header file replaces header file <ctype.h>
<fstream> Contains function prototypes for functions that perform input from
files on disk and output to files on disk. This header file replaces
header file <fstream.h>.
<climits> Contains the integral size limits of the system. This header file
replaces header file <limits.h>.
<cfloat> Contains the floating-point size limits of the system. This header
file replaces header file <float.h>.
<string> Contains the definition of class string from the C++ Standard
Library
<vector>, These header files contain classes that implement the C++
<list>, Standard Library containers. Containers store data during a
<deque>, program's execution.
<queue>,
<stack>,
<map>,
<set>,
<bitset>
<exception>, These header files contain classes that are used for exception
<stdexcept> handling.
<memory> Contains classes and functions used by the C++ Standard Library
to allocate memory to the C++ Standard Library containers.
<sstream> Contains function prototypes for functions that perform input from
strings in memory and output to strings in memory.
<iterator> Contains classes for accessing data in the C++ Standard Library
containers.
<limits> Contains classes for defining the numerical data type limits on
each computer platform.
<utility> Contains classes and functions that are used by many C++
Standard Library header files.
Mathematical Functions
Some of the important mathematical functions in header file <cmath> are
Function Meaning
log(x) logarithm of x
Function Meaning
Function
A function is a subprogram that acts on data and often returns a value. A
program written with numerous functions is easier to maintain, update and
debug than one very long program. By programming in a modular (functional)
fashion, several programmers can work independently on separate functions
which can be assembled at a later date to create the entire project. Each
function has its own name. When that name is encountered in a program, the
execution of the program branches to the body of that function. When the
function is finished, execution returns to the area of the program code from
which it was called, and the program continues on to the next line of code.
int main()
{
starline( ); // function call
cout<< "\t\tBjarne Stroustrup\n";
starline( ); // function call
return 0;
}
// function definition
void starline()
{
int count; // declaring a LOCAL variable
for(count = 1; count <=65; count++)
cout<< "*";
cout<<endl;
}
Argument To A Function
Sometimes the calling function supplies some values to the called function.
These are known as parameters. The variables which supply the values to a
calling function called actual parameters. The variable which receive the value
from called statement are termed formal parameters.
int main()
{
float radius;
cin>>radius;
area(radius);
return 0;
}
void area(float r)
{
cout<< “the area of the circle is”<<3.14*r*r<<”\n”;
}
Calling Of A Function
the function can be called using either of the following methods:
i) call by value
ii) call by reference
Call By Value
In call by value method, the called function creates its own copies of original
values sent to it. Any changes, that are made, occur on the function‟s copy of
values and are not reflected back to the calling function.
Call By Reference
In call be reference method, the called function accesses and works with the
original values using their references. Any changes, that occur, take place on
the original values are reflected back to the calling code.
Consider the following program which will swap the value of two variables.
#include<iostream> #include<iostream>
using namespace std; using namespace std;
void swap(int &, int &); void swap(int , int );
int main() int main()
{ {
int a=10,b=20; int a=10,b=20;
swap(a,b); swap(a,b);
cout<<a<<" "<<b; cout<<a<<" "<< b;
return 0; return 0;
} }
void swap(int &c, int &d) void swap(int c, int d)
{ {
int t; int t;
t=c; t=c;
c=d; c=d;
d=t; d=t;
} }
output: output:
20 10 10 20
Inline Function
Functions save memory space because all the calls to the function cause the
same code to be executed. The functions body need not be duplicated in
memory. When the complier sees a function call, it normally jumps to the
function. At the end of the function. it normally jumps back to the statement
following the call.
While the sequence of events may save memory space, it takes some extra
time. To save execution time in short functions, inline function is used. Each
time there is a function call, the actual code from the function is inserted
instead of a jump to the function. The inline function is used only for shorter
code.
inline int cube(int r)
{
return r*r*r;
}
It is possible to declare local and global variables of the same name. C++
provides the unary scope resolution operator (::) to access a global variable
when a local variable of the same name is in scope. A global variable can be
accessed directly without the unary scope resolution operator if the name of the
global variable is not the same as that of a local variable in scope.
Array
An array is a collection of data elements of same data type. It is described by a
single name and each element of an array is referenced by using array name
and its subscript no.
Declaration of Array
Type arrayName[numberOfElements];
For example,
int Age[5] ;
float cost[30];
Examples:
cout << age[4]; //print an array element
age[4] = 55; // assign value to an array element
cin >> age[4]; //input element 4
Arrays as Parameters
void Merge(int A[], int B[], int C[], int N, int M, int &K)
{
int I = 0, J = 0;
K = 0;
while (I < N && J < M)
{
if (A[I] < B[J])
C[K++] = A[I++];
else if (A[I] > B[J])
C[K++] = B[J++];
else
{
C[K++] = A[I++];
J++;
}
}
int T;
for (T = I; T < N; T++)
C[K++] = A[T];
for (T = J; T < M; T++)
C[K++] = B[T];
}
CPP Programming
Type arrayName[numberOfRows][numberOfColumn];
For example,
int Sales[3][5];
Examples:
cout << A[1][2]; //print an array element
A[1][2] = 13; // assign value to an array element
cin >> A[1][2]; //input element
Arrays as Parameters
#include <iostream>
using namespace std;
int main ()
{
int arr[4][3] ={{12, 29, 11},
{25, 25, 13},
{24, 64, 67},
{11, 18, 14}};
print(arr,4,3);
return 0;
}
The number of elements that can be stored in a string is always n-1, if the size
of the array specified is n. This is because 1 byte is reserved for the NULL
character '\0' i.e. backslash zero. A string is always terminated with the NULL
character.
Example:
char str[80];
In the above example, str can be used to store a string with 79 characters.
Initializing a string
Note: When the value is assigned to the complete string at once, the computer
automatically inserts the NULL character at the end of the string. But, if it is
done character by character, then we have to insert it at the end of the string.
Printing strings
Note: For gets( ) and puts(), the header file <cstdio> (formally stdio.h) has to
be included. puts() can be used to display only strings. It takes a line feed after
printing the string.
cin gets()
It takes the white space i.e. a It does not take the white
blank, a tab, or a new line space i.e. a blank, a tab, or a
character as a string new line character, as a string
terminator. terminator.
Example: Example:
char S[80]; char S[80];
cout << "Enter a string:”; cout << "Enter a string:";
cin>>S; gets(S);
cout puts()
Example: Example:
char S[80] = "Computers"; char S[80] = "Computers";
cout<<S<<S; puts(S);
puts(S);
Output:
ComputersComputers Output:
Computers
Computers
int main( )
{
char str[80];
cout<<"Enter a string:";
cin.getline(str,80);
for(int l=0; str[l]!='\0';l++); //Loop to find length
cout<<"The length of the string is : "<<l<<endl ;
for(int i=l-1;i>=0;i--) //Loop to display the string backwards
cout<<str[i];
return 0;
}
Function to count the number of words in a string
int length(char S[ ])
{
for(int i=0;S[i]!='\0';i++);
return i;
}
Structure
A structure is a collection of variable which can be same or different types. You
can refer to a structure as a single variable and to its parts as members of that
variable by using the dot (.) operator. The power of structures lies in the fact
that once defined, the structure name becomes a user-defined data type and
may be used the same way as other built-in data types, such as int, double,
char.
struct Student
{
int rollno, age;
char name[80];
float marks;
};
int main()
{
return 0;
}
Defining a structure
When dealing with the students in a school, many variables of different types
are needed. It may be necessary to keep track of name, age, Rollno, and
marks point for example.
struct Student
{
int rollno, age;
char name[80];
float marks;
};
Student is called the structure tag, and is your brand new data type, like int,
double or char.
int main()
{
// declare two variables of the new type
Student s1, s3;
………
………
return 0;
}
Alternate method of declaring variables of type struct:
struct Student
{
int rollno, age;
char name[80];
float marks;
} s1, s3;
s3 = s2;
struct Student
{
int rollno, age;
char name[80];
Day date_of_birth;
float marks;
};
s.date_of_birth.month = 11;
s.date_of_birth.date = 5;
s.date_of_birth.year = 1999;
typedef
It is used to define new data type for an existing data type. It provides and
alternative name for standard data type. It is used for self documenting the
code by allowing descriptive name for the standard data type.
for example:
It is user defined.
It works if you know in advance a finite list of values that a data type can
take.
The list cannot be input by the user or output on the screen.
Macros
Macros are built on the #define preprocessor. Normally a macro would look like:
#define square(x) x*x
Its arguments substituted for replacement text, when the macro is expanded.
CPP Programming
Pointer
POINTER
A pointer is a variable that holds a memory address, usually the location of
another variable in memory.
Memory layout
int arr[]={4,7,11};
int *ptr = arr;
What is ptr + 1?
It means (address in ptr) + (1 * size of an int)
cout << *(ptr+1); // displays 7
cout << *(ptr+2); // displays 11
Array Access
Array notation arr[i] is equivalent to the pointer notation *(arr + i)
#include<iostream>
using namespace std;
int main()
{
int a=10,b=20;
swap(&a, &b);
cout<<a<<" "<<b;
return 0;
}
void swap(int *x, int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
output:
20 10
Pointers to Constants and Constant Pointers
Pointers to Structures
We can create pointers to structure variables
Free store
Free store is a pool of unallocated heap memory given to a program that is used
by the program for dynamic allocation during execution.
To allocate array
double *dptr = new double[25];
Memory Leak
If the objects, that are allocated memory dynamically, are not deleted using
delete, the memory block remains occupied even at the end of the program.
Such memory blocks are known as orphaned memory blocks. These orphaned
memory blocks when increase in number, bring adverse effect on the system.
This situation is called memory leak
struct node
{
int data;
node* next;
}
CPP Programming
OOP Concepts
There are two common programming methods: procedural programming and
object-oriented programming (OOP). So far you have been creating procedural
programs.
Procedural Programming
In a procedural program data is typically stored in a collection of variables and
there is a set of functions that perform operations on the data. The data and the
functions are separate entities. Usually the variables are passed to the functions
that perform the desired operations. As you might imagine, the focus of
procedural programming is on creating the functions, or procedures, that
operate on the program‟s data. Procedural programming works well. However,
as programs become larger and more complex, the separation of a program‟s
data and the code that operates on the data can lead to problems.
An object is an entity that combines both data and procedures in a single unit.
An object‟s data items, also referred to as its attributes, are stored in member
variables. The procedures that an object performs are called its member
functions. This wrapping of an object‟s data and procedures together is called
encapsulation.
Not only objects encapsulate associated data and procedures, they also permit
data hiding. Data hiding refers to an object‟s ability to hide its data from code
outside the object. Only the object‟s member functions can directly access and
make changes to the object‟s data.
Where class_name is a valid identifier for the class. The body of the declaration
can contain members, that can be either data or function declarations, The
members of a class are classified into three categories: private, public, and
protected. private, protected, and public are reserved words and are called
member access specifiers. These specifiers modify the access rights that the
members following them acquire.
private members of a class are accessible only from within other members of
the same class. You cannot access it outside of the class.
protected members are accessible from members of their same class and also
from members of their derived classes.
Finally, public members are accessible from anywhere where the object is
visible.
By default, all members of a class declared with the class keyword have private
access for all its members. Therefore, any member that is declared before one
other class specifier automatically has private access.
Object Declaration
Once a class is defined, you can declare objects of that type. The syntax for
declaring a object is the same as that for declaring any other variable. The
following statements declare two objects of type circle:
Circle c1, c2;
#include <iostream>
using namespace std;
int main()
{
Circle c1; //define object of class circle
c1.setRadius(2.5); //call member function to initialize radius
cout << c1.getArea(); //display area of circle object
return 0;
}
CPP Programming
It is a member function having same name as it‟s class and which is used to
initialize the objects of that class type with a legal initial value. Constructor is
automatically called when object is created.
Types of Constructor
Default Constructor-: A constructor that accepts no parameters is known as
default constructor. If no constructor is defined then the compiler supplies a
default constructor.
Circle :: Circle()
{
radius = 0;
}
int main()
{
Circle c1; //default constructor invoked
Circle c2(2.5); //parmeterized constructor invoked
Circle c3(c2); //copy constructor invoked
cout << c1.getArea()<<endl;
cout << c2.getArea()<<endl;
cout << c3.getArea()<<endl;
return 0;
}
#include<iostream>
#include<iomanip>
using namespace std;
class Time
{
private :
int hour;
int minute;
int second;
public :
//constructor with default value 0
Time(int h = 0, int m = 0, int s = 0);
//setter function
void setTime(int h, int m, int s);
//print description of object in hh:mm:ss
void print();
//compare two time object
bool equals(Time);
};
int main()
{
Time t1(10, 50, 59);
t1.print(); // 10:50:59
Time t2; //object created with default value
t2.print(); // 00:00:00
t2.setTime(6, 39, 9); //set the new time in object
t2.print(); // 06:39:09
if(t1.equals(t2))
cout << "Two objects are equals\n";
else
cout << "Two objects are not equals\n";
return 0;
}
Output :
10:50:59
00:00:00
06:39:09
Two objects are not equals
Let's us discuss our Time class and add some new concepts of programming
Constructors with Default Arguments
Constant Function
In some cases, you will need that the member function should not change any
private member variables of the calling object. You can do this by adding const
to the end of the function declaration (prototype) and in the function definition.
class Time
{
...
...
//print description of object in hh:mm:ss
void print() const;
...
...
};
....
....
void Time :: print() const
{
cout << setw(2) << setfill('0') << hour << ":"
<< setw(2) << setfill('0') << minute << ":"
<< setw(2) << setfill('0') << second << "\n";
}
....
Constant Parameters
......
This means that equals() receives a copy of object t2 with name otherTime.
If a function needs to store or change data in an object‟s member variables, the
object must be passed to it by reference.