0% found this document useful (0 votes)
75 views

c3134 - Oops Notes - Module I

C++ was developed from C to support object-oriented programming. It is case sensitive and ignores whitespace. C++ programs include preprocessor directives, comments, declarations and definitions. A basic C++ program structure includes the #include directive, using namespace, main function, and I/O statements. Variables are defined with a type and can be used in expressions and statements.

Uploaded by

Soumya KS
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views

c3134 - Oops Notes - Module I

C++ was developed from C to support object-oriented programming. It is case sensitive and ignores whitespace. C++ programs include preprocessor directives, comments, declarations and definitions. A basic C++ program structure includes the #include directive, using namespace, main function, and I/O statements. Variables are defined with a type and can be used in expressions and statements.

Uploaded by

Soumya KS
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++

MODULE I - Basic Programming Concepts in C++

A Brief Overview of CPP

 developed from C by Bjarne Stroustrup, ie, C++ is a superset of C.


 to expand the power of C by supporting the object-oriented approach to programming.
 C++ is token oriented and case sensitive. The compiler breaks the source code into component
words regardless of their position on the line, and elements of the program code should not be
in specific columns. The programmers can use white space between tokens to format code for
readability, and the C++ compiler ignores all white spaces. Case sensitivity helps avoid name
conflicts but can result in errors if the programmer.
 C++ only has a few basic numeric data types. To compensate for the scarcity of built-in data types,
C++ supports data aggregation into composite types: arrays, structures, unions, and
enumerations; data aggregates can be combined to form other aggregates.
 C++ supports a standard set of flow control constructs: sequential execution of statements and
function calls, iterative execution of statements (for, while, do while), decision-making (if, switch),
jumps (break, continue, goto ).
 C++ is a structured language: Unnamed blocks of code can be nested to any depth, and variables
defined in inner blocks are not visible to the outer blocks.
 functions (i.e., a named block) cannot be nested inside another function.
 C++ functions can be called recursively in exactly the same way as C functions can.
 C++ functions can be placed in one file or in several source files. These files can be compiled and
debugged separately, thus enabling different programmers to work on different parts of the
project independently. Compiled object files can be linked together later to produce an
executable object file.
 C++ inherits from C support for the use of pointers for three purposes: a) passing parameters
from a calling function to a called function, b) dynamic memory allocation from the computer
heap (for dynamic data structures), and c) manipulating arrays and array components.
 supports Object Oriented Programming concept through Classes and objects.

Basic Program Structure


#include <iostream> // preprocessor directive
using namespace std; // compiler directive
int main(void) // function returns integer
{
int x,y; // definitions of variables
int z=1; // initialisation of variables
cout << “Enter two numbers:” ; // output to monitor

Dept. of Computer Engg 1 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
cin >> x>>y; // input from keyboard
z = x + y; // assignment statement
cout << “Sum: ” << z << endl;
return 0; // return statement
}

Preprocessor Directives
 Preprocessor directives are lines included in the code of programs preceded by a hash sign (#).
 These lines are not program statements but directives for the preprocessor. The preprocessor
examines the code before actual compilation of code begins and resolves all these directives
before any code is actually generated by regular statements.
#include <iostream>

 This directive causes the preprocessor to add the contents of the iostream file to the program.
 The header file iostream should be included at the beginning of all programs that use
input/output statements.

 #define arg1 arg2: The #define directive is also used for text substitution. Its first argument
specifies the text to be substituted, and the second argument specifies the text to be used as
the substitute.
Eg1: #define PI 3.14159266

 using namespace directive: It is not a preprocessor directive, but a compiler directive. It


instructs the compiler to recognize the code brought in by the header files.

Comments
 C++ has two types of comments: block comments (multi-line comments) and end-of-line
comments (single-line comments).
 Block comments start with a two-character symbol /* and end with a two-character symbol
*/.
 End-of-line comments start with a two-character symbol // and ends without a special symbol
but till the line ends.

eg: // this is an end-of-line comment


/* this is a block comment */
/* this is
a block comment too*/

Dept. of Computer Engg 2 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
Declarations and Definitions
 A token is the smallest element of a C++ program that is meaningful to the compiler. The
C++ parser recognizes these kinds of tokens: identifiers, keywords, literals, operators,
punctuators, and other separators.
 An identifier is a name given to denote a variable, constant, data type, function or label. To
make the program more readable, meaningful words can be given for identifiers. They can
start with a letter or an underscore '_' character only, not with a digit or any other special
character. Other characters of an identifier can be capital letters A-Z, lowercase letters a-z,
digits 0-9, or underscores. No other special symbols ($, #, etc.) or spaces are allowed.
 There are reserved words called keywords that cannot be used as programmer-defined
identifiers; they are all in lowercase. Here is the list of keywords that are common both to C
and C++ ;
auto break case char const continue default do

double else enum extern float for goto if int long

register return short signed sizeof static struct switch typedef

union unsigned void volatile while

 A variable is used to store a value. Before the identifier is used as a name for a variable in a
C++ the program, it has to be defined. The names of variables denote locations (addresses) in
computer memory that hold typed values. These values can change during program execution.
The keywords in their lowercase cannot be used as variables. The type of the variable describes
the range of values permissible for that type and the operations allowed over values of this
type.
 The definition establishes an association between the identifier and its type, reserving a
memory space for it based on the type; each definition ends with a semicolon as follows:
int num1, num2;

double sum;

char letter;

 Generally, declaration of a variable is same as its definition. But in C++, both are different.
While definitions associate the name of the variable with its type and allocate the space for
the variable, declarations only associate the name and the type, because the space for the
variable is allocated elsewhere.

Statements and Expressions


 A statement is a program unit that is executed as a logical whole so that its component steps
are hidden from the programmer. A program statement is an abstraction tool: It allows us to
concentrate on what is being done rather than on how this is done. For example,
declarations and definitions are statements. Each simple statement must end with a semi

Dept. of Computer Engg 3 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
colon.
 An expression is a statement containing operators and operands and evaluates a value.
Operands are either variables or literal numbers or smaller expressions.
eg: z = (y + 1) * (y – 1); // expression with subexpressions
 An assignment is a statement with a left-hand side and the right-hand side of an assignment
operator ('=').

Data and Expressions

Values and Their Types


C++ variables are associated with their types at the time of definition. The type describes three
characteristics of the value:
* the size of the values of that type in computer memory
* the set of values that are legal for the type
* the set of operations that are legal on the values of that type
For example, the values of type int are allocated four bytes, and the set of values ranges from -
231 to 231- 1 (-214,74,83,648 to +214,74,83,647). The set of operations includes assignment,
comparisons, shifts, arithmetic operations, etc.
Type names of built-in C++ types are reserved words: int, char, bool, float, double, and void.

Integral Type: On all computer architectures, the C++ integer type represents the most basic
type. The values of this type are always the fastest to operate on the given platform.

Character Type: The character type is treated by C++ as just another kind of integer. Its size is 1
byte (8 bits). It can represent any ASCII symbol: a letter, a digit, or a nonprintable control
character. Here are examples of definitions for character variables.
char abc;
char c = 'A', ch = 65; // both c and ch contain 'A'
Boolean Values: It has values true and false. These values are useful for computing logical
expressions and for choosing execution paths through the program code. The Boolean values
take only one byte of memory.
Eg: bool flag = false, result = true;
If we print the values flag and result defined above, the first one will be printed as zero (not as
false ), and the second one will be printed as one (not as true ).

Floating Point Types: Used to store fractional numbers. There are three floating point types in
C++: float, double, and long double. Usually, type float is allocated four bytes, type double is

Dept. of Computer Engg 4 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
allocated eight bytes, and type longdouble is allocated 10 bytes (or just eight bytes, the same as
for double ).
eg: float pi; double r; long double d;
float pi=3.14; double ra=5.3; long double db=530.0e-2;
All floating point literals without a qualifier are double values by default.

Flow control structures


They modify sequential flow of execution of statements. There are three kinds of flow control
statements:
1. conditional statements
2. loops
3. function calls

Conditional Statements
The simplest conditional statement is the if statement. Its general form is

if (testExpression)
{
// statements
}

 The if statement evaluates the test expression inside parenthesis.


 If test expression is evaluated to true, statements inside the body of if is executed.

Dept. of Computer Engg 5 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
if(num > 100){
cout<<"number is greater than 100";
}

If-else statement

Syntax:

if(condition) {
Statement(s);
}
else {
Statement(s);
}
The statements inside “if” would execute if the condition is true, and the statements inside “else”
would execute if the condition is false.

Example

if (b > a) {
cout << "b is greater";
} else {
cout << "a is greater";
}

Nested if...else
if (condition1)
{

Dept. of Computer Engg 6 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
Example
if (i < 15)
{
cout<<"i is smaller than 15";
if (i < 12)
cout<<"i is smaller than 12 too";
else
cout<<"i is greater than 15";
}

if-else-if ladder

Syntax:
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
example

if (i == 10)
cout<<"i is 10";
else if (i == 15)
cout<<"i is 15";
else if (i == 20)
cout<<"i is 20";
The 'switch' Statement:
 The switch statement is a tool for making multiway decisions in a program. It provides
alternative execution paths based on the value of an integral expression.
 The expression in parentheses follows the keyword switch. The rest of the statement consists
of branches that are placed within the braces.
 Each branch consists of the keyword case, a value of the same type as the switch expression, a
colon, and a set of one or more statements terminated by semicolons.

Dept. of Computer Engg 7 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
Syntax:
switch(expression)
{ // braces are mandatory
case ConstantExpr1: statements; //
first branch case ConstantExpr2:
statements;
.....
default: statements; // default branch
} // no semicolon after the closing brace

The switch expression can be only of type char, short, int, or long (integral types). Floating point
types ( float, double, or long double ) or programmer-defined types (arrays, structures, or classes)
are not allowed. Also. Each case statement block must have a break statement as the last statement
in order to avoid successive execution of the case blocks after that. The default branch is executed
if none of the case expressions match.

Iteration:
They are used for repetitive actions. C++ provides three iterative statements: while loops, do-while
loops, and for loops.

While:
* The while loop tests the loop condition to be true before each iteration through the loop
body and stops the iterations when the loop condition becomes false.
* The loop expression is tested before the first iteration itself and so it is an entry-controlled
loop. Thus the loop body will not be executed at all if the condition is false when it is first
checked.
Syntax:
while (expression)
{
statement;
}

Example:
int a = 1;
while( a <= 10 )
{
cout << "value of a: " << a;

Dept. of Computer Engg 8 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
a++;
}

do-while:
* The do - while loop is very similar to the while loop but it tests its condition at the bottom
of the loop body, after each iteration and the loop body will be executed at least once.
Since the condition is checked at the end of the loop body, this loop is called exit controlled
loop.

Syntax:
do
{
statements; // this is the loop body – simple or compound statement
}while(expression);

Example:

int a = 1;
do
{
cout << "value of a: " << a;
a++;
} while(a<=10);

for:
* The for loop is usually considered an appropriate loop when the number of repetitions is
known in advance, before the loop starts.
* This form of iteration brings together the three most important elements of the loop
design: initialization of the current value before the first iteration, evaluation of the current
value before the start of next iteration, and change of the current value after the iteration
(before the next iteration).
Syntax:
for (init; condition; IncrementExpr)
statement;
* The init step is executed first, and only once. This step allows you to declare and initialize
any loop control variables. You are not required to put a statement here, as long as a
semicolon appears.
* Next, the condition is evaluated. If it is true, the body of the loop is executed.
* After the body of the for loop executes, the flow of control jumps back up to the increment

Dept. of Computer Engg 9 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
statement. This statement allows you to update any loop control variables.

Eg:
for(int a=1; a<=10; a++)
{
cout << "value of a: " << a;
}

C++ Jump Statements


* Jump statements are used to alter the flow of control unconditionally.
* The jump statements defined in C++ are break, continue, goto and return.
* In addition to these jump statements, a standard library function exit () is used to jump out
of an entire program.
The 'break' Statement: The break statement is extensively used in loops and switch statements. A
break statement immediately terminates the loop or the switch statement, bypassing the
remaining statements. The control then passes to the statement that immediately follows the loop
or the switch statement.
The 'continue' Statement: The continue statement is used to 'continue' the loop with its next
iteration. In other words, continue statement skips any remaining statements in the current
iteration and immediately passes the control to the next iteration.
The 'goto' Statement: The goto statement can be used anywhere within a function or a loop. As
the name suggests, goto statements transfer the control from one part to another part in a
program which is specified by a label. Labels are user-defined identifies followed by a colon.
The 'return' Statement: The return statement represents a jump that terminates the execution of
the executing function and go back to the calling function.
The 'exit()' Function: The exit( ) function is a standard library function (in 'cstdlib' header file) that
terminates the entire program immediately and passes the control to the operating system.

Arrays as Homogeneous Aggregates

An array is a set of elements of the same datatype, represented by a single name.


Eg : int mark[5];

* Arrays are useful when we have to process a number of similar data many times. For eg:

Dept. of Computer Engg 10 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
marks of 20 students, salary of 10 employees.
* Each element of an array will not have name, but can be accessed using the array name with
a subscript or index.
* In C++, an array of n elements will have indices ranging from 0 to n-1.
* Arrays are finite. Their length cannot be changed during the program execution.
Define an array:
Syntax: data type array_name[max_size];

Initialising an array:
int hours[7] = { 8, 8, 12, 8, 4, 0, 0 }; // 7 values
int hours[] = { 8, 8, 12, 8, 4, 0, 0 };

* An element of the array can be accessed by the form array_name[index].

Multidimensional Arrays
* C++ supports multidimensional arrays. Theoretically, there is no limit to the number of array
dimensions.
* When defining a multidimensional array, specify the type of array components, the name of
the array, and, in separate brackets, the number of elements in the first direction, number of
elements in the second direction, and so on.
Eg: int m[2][3]; // 2 dimensional array. 2 rows of arrays, 3 elements each, total 6 int elements

Initialisation:
int m[2][3] = { 10, 20, 30, 40, 50, 60 }; // just like a one-d array
int m[2][3] = { { 10, 20 }, {30, 40 } };

* Access to an element of the multidimensional array requires several indices, one for each
dimension. Each index starts from 0, reaching one less than the maximum.

Character Arrays
* Character arrays are often called as strings. Since there is no array-boundary checking in C++,
the programmer has to take care of the length of the array. For character array, the end of
the array can be indicated by numeric Zero. This end character is called zero terminator
character or just the terminator. It is represented as '\0'.
Eg: char t[4] = { 'H','i','!','\0' }; // it displays “Hi!”. It has a length of 4 (including
the terminator). char t[4] = { 'H','i','!',0 }; // same as above
char t[] = { 'H','i','!',0 }; // same as above

Operations on Character Arrays

Dept. of Computer Engg 11 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
A number of string manipulation functions are available in C++ by including the “cstring”
header file.
String Copy: strcpy
Syntax: strcpy(char_array_destn, char_array_source);
It copies the content of char_array_source until the first terminator to char_array_destn including
that terminator.
strcpy(str2,str1); // now str2 will be “hi”

String Concatenation: strcat


Syntax: strcat(str_destn, str_source);
Appends a copy of the source string to the destination string. This function returns the destination
string.
eg: char str1[30]=”good”, str2[30] = “morning”;
strcat(str1, str2); // str1 becomes “goodmorning”

String Comparison: strcmp() Syntax: strcmp(str1, str2);


It implements the comparison operation for its two character array arguments str1 and str2. It
compares the corresponding characters one after another until it either finds two different
characters at the same displacement or reaches the first terminator. If the function reaches both
terminator at the same displacement, it returns 0 and the strings are considered the same. If the
function finds two different characters, and if the different character in str1 is less than that of str2
(ASCII Values), the function returns -1. If it is greater, it returns 1.
eg: strcmp(“goodafternoon”,“goodafternoon”); // returns 0
strcmp(“goodAfternoon”,“goodafternoon”); // returns -1. ASCII of 'A' is
65, 'a' is 97 strcmp(“goodafternoon”,“goodAfternoon”); // returns 1.

String Length: strlen() Syntax: strlen(str);


It returns the length of the string str, ie, the number of characters in the string just before
the terminator. eg: strlen(“good”); // return 4, ie without the terminator
sizeof(“good”); // returns 5, ie with the terminator

Two dimensional character array


These are just like 2D integer array and can be treated as a single
array of strings. eg: char strArray[3][15] ;
char str1[][15]={"sunday","monday","tuesday","wenesday"};

Structures as Heterogenous Aggregates

Dept. of Computer Engg 12 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
 A structure allows you to wrap one or more variables that may be in different data types
into one.
 It can contain any valid data type like int ,char, float, array, pointer or even structures.
 Each variable in the structure is called a structure member.

Defining a structure
To define a structure, you use the struct keyword.

struct struct_name
{
Data type variable 1;
Data type variable 2;

Data type variable n;
};

The following example defines the person structure:

struct person{
char first[32]; //first field an array of chars
char last[32]; //second field an array of chars
int age; //third field an int
};

Note that the above code is only defining a person structure. There are two ways to
declare a structure variable:

Declaring a structure
You can declare structure variables together with the structure defintion:

struct struct_name {
structure_member;
...
} var_1,var_2, var_n;

Or, you can declare the structure variable after you define the structure:

struct struct_name var_1,var_2, var_n;

Dept. of Computer Engg 13 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
Accessing a structure member
To access a structure member, we use the dot operator ‘ . ‘ between the structure name
and member:

structure_name.structure_member

The following example demonstrates how to access the first name of structure
person:

person student;

student.first = "Richard";
Array of Structures
Just like you can have an array of any data type, you can have an array of structures.
struct person{
char first[32]; //first field an array of chars
char last[32]; //second field an array of chars
int age; //third field an int
};

person students[60]; //array of struct person

Union
 A union in C programming is a user defined data type which may hold members of different
sizes and type.
 Union uses a single memory location to hold more than one variables. However, only one of
its members can be accessed at a time and all other members will contain garbage values.
 The memory required to store a union variable is the memory required for the largest
element of the union.

Defining a Union
union person {
char name;
int age;
double height;
};

Dept. of Computer Engg 14 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
Declaring a Union

Since the union is still a type of structure the method for declaring it is as follows:

union person {
char name;
int age;
double height;
}newPerson;
Or
Person newPerson;

Initializing a Union

The process of initializing variables in a union is the same as a union but the results are what make
unions unique. The dot operator is still used in order to reach the data types inside of the union.

Person newPerson;
newPerson.age = 20;
newPerson.height = 6.2;

Once the height variable is initialized the variable age is overwritten and no longer exists.

Difference between Structures and Union

Structure Union

A structure is defined with ‘struct’ keyword A union is defined with ‘union’ keyword

All members of a structure can be manipulated The members of a union can be manipulated only
simultaneously one at a time
The size of a structure object is equal to the sum The size of the union object is equal to the size of
of the individual sizes of the member objects the largest member object.
Structure members are allocated distinct Union members share common memory space
memory location. for their exclusive usage.

Structures are not considered as memory


Unions are considered as memory efficient
efficient in comparison to unions.

Dept. of Computer Engg 15 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++

Enumerations, and Bit Fields


Enumerations:
 Enumeration types allow the programmer to define variables that accept values only from a
defined set of identifiers.
 The keyword enum is used to introduce the programmer- defined type name similar to struct
or union and has braces with ending semicolon.
Eg: enum Color { RED, GREEN, YELLOW } ;
Here the elements will have the default values starting with 0,1,2,..

enum Color { RED, GREEN=8, YELLOW } ; //red = 0 and YELLOW is 9 now

enum Status { CLEAR = 2, FULL = 8, EMPTY = 64 } ;

The advantage of this approach is speed.

Bit Fields :

 Classes and structures can contain members that occupy less storage than an integral type.
These members are specified as bit fields. The syntax for bit-field member-
declarator specification follows:

Syntax

declarator : constant-expression

Example :

struct Date {
unsigned short nWeekDay : 3; // 0..7 (3 bits)
unsigned short nMonthDay : 6; // 0..31 (6 bits)
unsigned short nMonth : 5; // 0..12 (5 bits)
unsigned short nYear : 8; // 0..100 (8 bits)

};

Memory Management: the Stack and the Heap


 In all programs, programmers define variables in their code and for each variable a finite
amount of memory is allocated during the compile time based on its type.
 This is happened in the area of memory called stack.
 When the program needs more space for dynamic unnamed variables, the memory is
allocated from the area called heap.

Dept. of Computer Engg 16 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
Scope of Variable:
The scope of a variable is the area of the program where the variable is valid.
The four types of scopes are;

 block scope : The opening and closing curly braces delimit the block scope.
 function scope : The function scope is also delimited by the opening and closing curly braces.
The difference between the block and the function scope is that the function has parameters
(and their names are known within the scope) and the name. The function scope is entered
during execution when the function is called.
 file scope : The file scope is delimited by the physical boundaries of the file. It can contain type
definitions, definitions and declarations of variables, and definitions and declarations of
functions.
 the scope of the whole program : The program scope has no delimiters. Anything belonging to
any source file that is part of the program is within the program scope.

Scope enables the programmer to define variables of the same name at different areas of the code.
For example if we define a variable in our code and inside a block after that with the same name,
the outside variable cannot be accessed inside the block.

Eg:
int j=10;
{
int j=2;
cout<<j<<endl; //will print 2
}
cout<<j; // will print 10

Scope rules help us avoid name conflicts and excessive communications among programmers.

Memory Management: Storage Classes


 The scope of a program variable is a characteristic which defines the area where that variable
is known. However, it does not define when memory is allocated for a particular variable
during execution and when this memory is taken away and made available for other uses. The
rules of memory allocation at run time depend on another characteristic of programmer-
defined names: their storage class.

 Storage class refers to a span of execution time when the association between a name of a variable
and its location in memory exists.

Dept. of Computer Engg 17 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
 In the process of program execution, program variables (objects) can be allocated in three
areas of memory reserved for the program: stack memory, and heap memory.

 Variables defined as local to a function or block are placed on the stack.

 In addition, C++ supports dynamic variables. Dynamic variables are allocated on the program
heap.

C++ storage classes can be specified using the following keywords.


* auto: default for variables defined as local in a block scope or in a function scope (automatic
variables)
* extern: can be applied to variables that are global in file scope .
* static: can be used for global variables in a file scope or for local variables defined in a block or
in a function scope .
* register: used for variables kept in high-speed registers rather than in random-access memory.
extern and static variables are allocated in the fixed data memory of the program, auto
variables are allocated on the program stack, and register variables are allocated in registers if
possible. If there are not enough registers available, these variables are allocated either in the fixed
area (for global variables) or on the program stack (for local variables).
Automatic Variables
 Automatic variables are the local variables defined in functions or in blocks. The auto
specifier is used to denote these variables, but this specifier need not be used since auto is
the dafault specifier for functions and blocks.

Eg: auto int j=10; // auto if it is inside a block or function, otherwise cause error

int k; // this is also auto if it is inside a block or function otherwise it is global

External Variables (Global Variables)


 External variables are variables that are defined outside any function. Their scope is the file
they are declared in, from the place of definition until the end of file. The name is not visible
in another file, hence it cannot be used in another file to refer to the same variable.
 A global variable defined in one file can be referenced from other files in the application by
using the 'extern' keyword.

Static Variables
Static variables are local variables defined in a function (or in an unnamed block) so that their values

1. should survive from one function call to another (or from one scope execution to another).
2. Static storage class is also used to define global variables that should be accessed by the
code only in

Dept. of Computer Engg 18 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
the same file where the variables are defined but not by the code in other files .
Static variables are specified by the keyword static. They are implicitly initialized to 0 . Eg: static int
count=0;

The static variable is stored in the fixed memory and has a life span is from the start of the variable
definition (program – in the case 2), to the end of its execution. But the name is not known outside
of the braces (file – in the case 2) where the variable is defined.

Register Variables
 The register storage class is used to define local variables just like the auto variables but are
stored in a register instead of memory. The number of register variables that can be defined
depends on the number of free registers available.
Eg: register int count=0;

Memory Management: Using Heap


 Memory for program variables are allocated in the fixed or stack memory area, but there are
situations where the memory must be allocated dynamically, especially for unnamed
variables.
 Dynamic memory management is used for this purpose by allocating and reallocating memory
dynamically. This memory is allocated from an area called the heap.
A pointer is an ordinary named-variable that contains an address of another variable, which
can be a conventional (named) stack variable. However, pointers usually point to variables allocated
on the heap (unnamed variables). Pointers themselves, however, are commonly allocated either in
the fixed data section (as global or static) or on the stack (as auto). The scope and lifetime of a pointer
is same as that of a normal variable. Pointer variables (addresses) are often of the size of integers
regardless of the type of the values they point to.

In C++, pointers are usually used for the following:


* dynamic allocation of arrays of size specified at run-time size
* building dynamic data structures composed of noncontiguous linked nodes
* passing parameters to functions
A pointer is defined by specifying the type of data it has to point, an asterisk symbol (*) and
the pointer name itself. To access the value of the object that the pointer points to, the

Dept. of Computer Engg 19 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
dereferencing operator (asterisk *) can be used. This process is called dereferencing a pointer.
Pointers can be initialized to point to named variables with the use of address-of operator (reference
operator &).
Pointers may contain addresses of objects of built-in and programmer defined types, their arrays,
functions and other pointers.
Eg: int *p; // 'p' is the pointer name. 'p' points to a memory that can hold an
integer. char* pc, pchar; // pc is a pointer to a char type, but pchar is of
type char, not char*

char* pc, *pchar; // both pc and pchar are pointers to


char types char** pcc; //pcc - a pointer to a character
pointer

When a local pointer (automatic variable) is not initialized, it contains a random bit pattern like any
other automatic variable. This pattern can be interpreted as an address, but this address can be
anywhere in memory. Reading from this location returns garbage; writing to this location corrupts
computer memory. It might crash the operating system, cause run-time memory protection
exception, produce incorrect results, or even produce correct results (if the location pointed to by
the pointer is not used by the program). Using noninitialized pointers is a common error, and it is
hard to diagnose because they can point to any area in memory.

eg:
int *p,*r; // two integer
pointers p and r int q=10;

Allocating Memory on the Heap


In C++, the new and delete are two unary operators used allocate and deallocate memory from heap
(C uses
malloc(), calloc() functions to allocate dynamic memory and free() to deallocate it).
The operator new takes a datatype as its operand and tries to allocate a space in heap equal to the
size of that datatype. If the allocation is successful, it returns the address of that location. We can
assign this address to apointer of the same type. If the allocation is not successful, it returns 0 and
the programmer can decide what to do next (for example, print a message and terminate).
Eg:
int *pi; // noninitialized pointer
pi = new int; // get unnamed space, point to it
if (pi == NULL) // if new fails, it returns zero
{ cout << "Out of memory\n"; return 0; }

The operator delete takes the name of a pointer as its operator. It finds the area on the heap pointed
to by its operand pointer and asks the operating system to mark this location (of the size defined by

Dept. of Computer Engg 20 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
the type in the pointer definition) as unused. After you delete the heap variable pointed to by a
pointer, the pointer becomes noninitialized again and should not be used for dereferencing. Also,
deleting memory twice is a run-time error.
Eg: delete pi;

It is very important to use delete operator corresponding to each new to avoid memory leakage.
Since C++ is backward compatible with C, malloc() and free() are supported in C++. They are defined
in the cstdlib standard library.

Input and Output with Disk Files


Output to File:
 Writing data to a disk file is similar to writing data to the monitor screen, but instead of the
predefined object cout we use a programmer-defined object of the library class ofstream
(output file stream).
 This class is defined in the library header file fstream that has to be included in the source
code.
 We define an object of the class ofstream and output the contents to that object instead of
cout. If the disk file with this name does not exist, it is created.
 If the file with this name exists, it is silently deleted and a new empty file with the same name
is created. But if the file cannot be created, it will not make any error messages. One way to
deal with this problem is to call the member function fail() that returns true if the previous
I/O operation fails (for any reason) and false if it is successfully completed.
Eg:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream f("data.out"); // make an object f of class ofstream and opens the file data.out

if (f.fail()) // true if file open fails, false if file is opened successfully


{
cout << "Cannot open file";
return 0;
}
f<<"Hai friends"; // 'cout' is replaced by 'f'
return 0 ;
}

Dept. of Computer Engg 21 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
Input from File:
 Similar to class ofstream, class ifstream is defined in the header file fstream, which should
be included in the source file. Again, similar to class ofstream, the name of the physical disk
file is used as a parameter for the object.
 Call the member function fail() that returns true if the previous I/O operation fails (for any
reason) and false if it is successfully completed. After that, you can use the extraction
operator >> to read data into the program variables, using the object ‘f’ instead of ‘cin’.
 The function f.eof() returns true if the file has reached its end.

Eg: #include<iostream>
#include<fstream>
using namespace std; int main()
{
char c;
ifstream f("1.cpp");
if(f.fail())
{
cout<<"Error in opening file";
return 1;
}
do {
f>>c; // read each character
if(f.eof()) break;
cout<<c;
}while(1);
return 0;
}

But the >> operator has chances of errors. It will not read white spaces or new lines. Hence we use
functions get() and getline().

(1) get()

char c;
ifstream f("1.cpp");
do
{
f.get(c); //read each character to c
if(f.eof()) break; // check if reached end-of-file cout<<c;
}while(1);

Dept. of Computer Engg 22 Gptc Kalamassery


C3134 - OBJECT ORIENTED PROGRAMMING THROUGH C++
(2) getline()

char c[100];
ifstream f("1.cpp");
do
{
f.getline(c,90); // reads line, maximum 90 characters
if(f.eof()) break;
cout<<c;
}while(1);

Dept. of Computer Engg 23 Gptc Kalamassery

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy