SlideShare a Scribd company logo
1 of 19
1. C++ Scope Resolution Operator:: 
2. Pointers 
C++ Scope Resolution Operator:: 
http://publib.boulder.ibm.com/infocenter/comphelp/v7v91/index.jsp?topic=% 
2Fcom.ibm.vacpp7a.doc%2Flanguage%2Fref%2Fclrc05cplr175.htm 
The :: (scope resolution) operator is used to qualify 
hidden names so that you can still use them. You can 
use the unary scope operator if a namespace scope or 
global scope name is hidden by an explicit declaration 
of the same name in a block or class. For example: 
int count = 0; 
int main(void) { 
int count = 0; 
::count = 1; // set global count to 1 
count = 2; // set local count to 2 
return 0; 
} 
 The declaration of count declared in the main() 
function hides the integer named count declared 
in global namespace scope. 
 The statement ::count = 1 accesses the 
variable named count declared in global 
namespace scope. 
 You can also use the class scope operator to 
qualify class names or class member names.
 If a class member name is hidden, you can use it 
by qualifying it with its class name and the class 
scope operator. 
Example: 
The declaration of the variable X hides the class type 
X, but you can still use the static class member count 
by qualifying it with the class type X and the scope 
resolution operator. 
#include <iostream> 
using namespace std; 
class X 
{ 
public: 
static int count; 
}; 
int X::count = 10;// define static data member 
int main () 
{ 
int X = 0; // hides class type X 
// use static member of class X 
cout << X::count << endl; 
}
C++ Scope Resolution Operator :: 
PURPOSE 
C++The :: (scope resolution) operator is used to 
qualify hidden names so that you can still use 
them. 
You can use the unary scope operator if a 
namespace scope or global scope name is 
hidden by an explicit declaration of the same 
name in a block or class. 
Namespaces 
Namespaces allow to group entities like classes, 
objects and functions under a name. 
In this way the global scope can be divided in 
"sub-scopes", each one with its own name. 
The format of namespaces is: 
namespace identifier 
{ 
entities 
} 
Where identifier is any valid identifier and 
entities is the set of classes, objects and 
functions that are included within the 
namespace.
For example: 
namespace myNamespace 
{ 
int a, b; 
} 
In this case, the variables a and b are normal 
variables declared within a namespace called 
myNamespace. 
In order to access these variables from outside 
the myNamespace namespace we have to use 
the scope operator :: 
For example, to access the previous variables 
from outside [myNamespace=] we can write: 
general::a 
general::b 
The functionality of namespaces is especially 
useful in the case that there is a possibility that 
a global object or function uses the same 
identifier as another one, causing redefinition 
errors.
For example: 
// namespaces 
#include <iostream> 
using namespace std; 
namespace first 
{ 
int var = 5; 
} 
namespace second 
{ 
double var = 3.1416; 
} 
int main () { 
cout << first::var << endl; 
cout << second::var << endl; 
return 0; 
} 
EXAMPLE OUTPUT: 
5 
3.1416 
In this case, there are two global variables with 
the same name: var. One 
is defined as an int within the namespace first 
and the other one in defined 
as a double in the namespace called second. No 
redefinition errors happen 
thanks to namespaces.
The 'using' Keyword 
The keyword using is used to introduce a name 
from a namespace into 
the current declarative region. For example: 
// using example 
#include <iostream> 
using namespace std; 
namespace first 
{ 
int x = 5; 
int y = 10; 
} 
namespace second 
{ 
double x = 3.1416; 
double y = 2.7183; 
} 
int main () { 
using first::x; 
using second::y 
cout << x << endl; 
cout << y << endl; 
cout << first::y << endl; 
cout << second::x << endl; 
return 0; 
} 
EXAMPLE OUTPUT: 
5 
2.7183 
10 
2.7183
Notice how in this code, x (without any name 
qualifier) refers to first::x 
whereas y refers to second::y, exactly as our 
using declarations have 
specified. We still have access to first::y and 
second::x using their 
fully qualified names. 
The keyword using can also be used as a 
directive to introduce an entire 
namespace: 
// using example 
#include <iostream> 
using namespace std; 
namespace first 
{ 
int x = 5; 
int y = 10; 
} 
namespace second 
{ 
double x = 3.1416; 
double y = 2.7183; 
} 
int main () { 
using namespace first; 
cout << x << endl; 
cout << y << endl; 
cout << second::y << endl; 
cout << second::x << endl; 
return 0; 
}
EXAMPLE OUTPUT: 
5 
10 
3.1416 
2.7183 
In this case, since we have declared that we 
were using namespace first, all direct uses of x 
and y without name qualifiers were referring to 
their declarations in namespace first. 
using and using namespace have validity 
only in the same block in which they are stated 
or in the entire code if they are used directly in 
the global scope. 
For example, if we had the intention to first use 
the objects of one namespace and then those of 
another one, we could do something like:
// using namespace example 
#include <iostream> 
using namespace std; 
namespace first 
{ 
int x = 5; 
} 
namespace second 
{ 
double x = 3.1416; 
} 
int main () 
{ 
// Here are two blocks 
{ 
using namespace first; 
cout << x << endl; 
} 
{ 
using namespace second; 
cout << x << endl; 
} 
return 0; 
} 
EXAMPLE OUTPUT: 
5 
3.1416
What Are Pointers? 
Reference: 
http://www.tutorialspoint.com/cplusplus/cpp_pointers.htm 
 C++ pointers are easy and fun to learn. 
 Some C++ tasks are performed more easily with 
pointers, and 
 other C++ tasks, such as dynamic memory allocation, 
cannot be performed without them. 
As you know every variable is a memory location and every 
memory location has its address defined which can be 
accessed using 
ampersand (&) operator which denotes an address in 
memory. Consider the following which will print the address 
of the variables defined:#include <iostream> 
using namespace std; 
int main () 
{ 
int var1; 
char var2[10]; 
cout << "Address of var1 variable: "; 
cout << &var1 << endl; 
cout << "Address of var2 variable: "; 
cout << &var2 << endl; 
return 0; 
} 
When the above code is compiled and executed, it produces result something as follows: 
Address of var1 variable: 0xbfebd5c0 
Address of var2 variable: 0xbfebd5b6
What Are Pointers? 
 A pointer is a variable whose value is the address of 
another variable. 
 Like any variable or constant, you must declare a 
pointer before you can work with it. 
 The general form of a pointer variable declaration is: 
type *variablename; 
Here, type is the pointer's base type; it must be a valid C++ type and 
variablename is the name of the pointer variable. 
The asterisk you used to declare a pointer is the same asterisk that you use for 
multiplication. 
However, in this statement the asterisk is being used to designate a variable as 
a pointer. Following are the valid pointer declaration: 
int *ip; // pointer to an integer 
double *dp; // pointer to a double 
float *fp; // pointer to a float 
char *ch // pointer to character 
The actual data type of the value of all pointers, whether 
integer, float, character, or otherwise, is the same, a long 
hexadecimal number that represents a memory address. The 
only difference between pointers of different data types is 
the data type of the variable or constant that the pointer 
points to.
There are few important operations Using Pointers in C++: 
Which we will do with the pointers very frequently: 
(a) We define pointer variables 
(b) Assign the address of a variable to a pointer and 
(c) Finally access the value at the address available in the pointer variable. 
This is done by using unary operator * that returns the value of the variable 
located at the address specified by its operand. Following example makes use 
of these operations: 
#include <iostream> 
using namespace std; 
int main () 
{ 
int var = 20; // actual variable declaration. 
int *ip; // pointer variable 
ip = &var; // store address of var in pointer variable 
cout << "Value of var variable: "; 
cout << var << endl; 
// print the address stored in ip pointer variable 
cout << "Address stored in ip variable: "; 
cout << ip << endl; 
// access the value at the address available in pointer 
cout << "Value of *ip variable: "; 
cout << *ip << endl; 
return 0; 
}
When the above code is compiled and executed, it produces 
result something as follows: 
Value of var variable: 20 
Address stored in ip variable: 0xbfc601ac 
Value of *ip variable: 20 
C++ Pointers in Detail: 
Pointers have many but easy concepts and they are very 
important to C++ programming. There are following 
few important pointer concepts which should be clear 
to a C++ programmer: 
Concept Description 
C++ Null Pointers 
C++ supports null pointer, which is a 
constant with a value of zero defined in 
several standard libraries. 
C++ pointer arithmetic 
There are four arithmetic operators 
that can be used on pointers: ++, --, +, - 
C++ pointers vs arrays 
There is a close relationship between 
pointers and arrays. Let us check how? 
C++ array of pointers 
You can define arrays to hold a number 
of pointers. 
C++ pointer to pointer 
C++ allows you to have pointer on a 
pointer and so on. 
Passing pointers to 
functions 
Passing an argument by reference or by 
address both enable the passed 
argument to be changed in the calling 
function by the called function. 
Return pointer from 
functions 
C++ allows a function to return a 
pointer to local variable, static variable 
and dynamically allocated memory as 
well.
C++ NULL Pointers 
 It is always a good practice to assign the pointer NULL to 
a pointer variable in case you do not have exact address 
to be assigned. 
 This is done at the time of variable declaration. A pointer 
that is assigned NULL is called a null pointer. 
 The NULL pointer is a constant with a value of zero 
defined in several standard libraries, including iostream. 
Consider the following program: 
#include <iostream> 
using namespace std; 
int main () 
{ 
int *ptr = NULL; 
cout << "The value of ptr is " << ptr ; 
return 0; 
} 
When the above code is compiled and executed, it 
produces following result: 
The value of ptr is 0 
To check for a null pointer you can use an if statement as follows: 
if(ptr) // succeeds if p is not null 
if(!ptr) // succeeds if p is null
C++ Pointer Arithmetics 
 As you understood pointer is an address which is a 
numeric value. Therefore, you can perform arithmetic 
operations on a pointer just as you can a numeric value. 
 There are four arithmetic operators that can be used on 
pointers: ++, --, +, and - 
ptr++ 
 the ptr will point to the location 1004 because each time 
ptr is incremented, it will point to the next integer 
. 
 This operation will move the pointer to next memory 
location without impacting actual value at the memory 
location. 
 If ptr points to a character whose address is 1000, then 
above operation will point to the location 1001 because 
next character will be available at 1001.
Incrementing a Pointer: 
 We prefer using a pointer in our program instead of an array 
because the variable pointer can be incremented, unlike the 
array name which cannot be incremented because it is a 
constant pointer. 
 The following program increments the variable pointer to 
access each succeeding element of the array: 
#include <iostream> 
using namespace std; 
const int MAX = 3; 
int main () 
{ 
int var[MAX] = {10, 100, 200}; 
int *ptr; 
// let us have array address in pointer. 
ptr = var; 
for (int i = 0; i < MAX; i++) 
{ 
cout << "Address of var[" << i << "] = "; 
cout << ptr << endl; 
cout << "Value of var[" << i << "] = "; 
cout << *ptr << endl; 
// point to the next location 
ptr++; 
} 
return 0; 
}
Pointers and arrays are strongly related. 
In fact, pointers and arrays are interchangeable in many cases. 
For example, a pointer that points to the beginning of an array 
can access that array by using either pointer arithmetic or 
array-style indexing. Consider the following program: 
#include <iostream> 
using namespace std; 
const int MAX = 3; 
int main () 
{ 
int var[MAX] = {10, 100, 200}; 
int *ptr; 
// let us have array address in pointer. 
ptr = var; 
for (int i = 0; i < MAX; i++) 
{ 
cout << "Address of var[" << i << "] = "; 
cout << ptr << endl; 
cout << "Value of var[" << i << "] = "; 
cout << *ptr << endl; 
// point to the next location 
ptr++; 
} 
return 0; 
}
When the above code is compiled and executed, it 
produces result something as follows: 
Address of var[0] = 0xbfa088b0 
Value of var[0] = 10 
Address of var[1] = 0xbfa088b4 
Value of var[1] = 100 
Address of var[2] = 0xbfa088b8 
Value of var[2] = 200 
MORE EXAMPLES 
#include <iostream> 
using namespace std; 
const int MAX = 3; 
int main () 
{ 
int var[MAX] = {10, 100, 200}; 
int *ptr[MAX]; 
for (int i = 0; i < MAX; i++) 
{ 
ptr[i] = &var[i]; // assign the address of integer. 
} 
for (int i = 0; i < MAX; i++) 
{ 
cout << "Value of var[" << i << "] = "; 
cout << *ptr[i] << endl; 
} 
return 0; 
} 
When the above code is compiled and executed, it produces following 
result: 
Value of var[0] = 10 
Value of var[1] = 100 
Value of var[2] = 200 
You can also use an array of pointers to character to store 
a list of strings as follows: 
#include <iostream>
using namespace std; 
const int MAX = 4; 
int main () 
{ 
char *names[MAX] = { 
"Zara Ali", 
"Hina Ali", 
"Nuha Ali", 
"Sara Ali", 
}; 
for (int i = 0; i < MAX; i++) 
{ 
cout << "Value of names[" << i << "] = "; 
cout << names[i] << endl; 
} 
return 0; 
} 
When the above code is compiled and executed, it produces following result: 
Value of names[0] = Zara Ali 
Value of names[1] = Hina Ali 
Value of names[2] = Nuha Ali 
Value of names[3] = Sara Ali

More Related Content

What's hot

Call by value
Call by valueCall by value
Call by valueDharani G
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in clavanya marichamy
 
class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++Nilesh Dalvi
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphismlalithambiga kamaraj
 
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...Jayanshu Gundaniya
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).pptAlok Kumar
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++Sujan Mia
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingNilesh Dalvi
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingKumar
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)Ritika Sharma
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programmingprogramming9
 

What's hot (20)

Call by value
Call by valueCall by value
Call by value
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in c
 
class and objects
class and objectsclass and objects
class and objects
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
Function in c
Function in cFunction in c
Function in c
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
 
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
 

Viewers also liked

Material and energy balance
Material  and energy balanceMaterial  and energy balance
Material and energy balanceMagnusMG
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functionsMarlom46
 
Chemical and process engineering by ranjit hirode
Chemical and process engineering by ranjit hirodeChemical and process engineering by ranjit hirode
Chemical and process engineering by ranjit hirodeRanjit T Hirode
 
Chemical engineering Introduction to Process Calculations Stoichiometry
Chemical engineering Introduction to Process Calculations StoichiometryChemical engineering Introduction to Process Calculations Stoichiometry
Chemical engineering Introduction to Process Calculations StoichiometryHassan Salem
 
Material and Energy Balance
Material and Energy BalanceMaterial and Energy Balance
Material and Energy BalanceMagnusMG
 
Rehabilitación de Pozos Petroleros
Rehabilitación de Pozos PetrolerosRehabilitación de Pozos Petroleros
Rehabilitación de Pozos PetrolerosMagnusMG
 
Introduction to Chemical Engineering
Introduction to Chemical EngineeringIntroduction to Chemical Engineering
Introduction to Chemical EngineeringSAFFI Ud Din Ahmad
 
Process design for chemical engineers
Process design for chemical engineersProcess design for chemical engineers
Process design for chemical engineersAmanda Ribeiro
 
Concept Of C++ Data Types
Concept Of C++ Data TypesConcept Of C++ Data Types
Concept Of C++ Data Typesk v
 
Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Liju Thomas
 

Viewers also liked (19)

Operators in C++
Operators in C++Operators in C++
Operators in C++
 
C++ io manipulation
C++ io manipulationC++ io manipulation
C++ io manipulation
 
Cement Industries
Cement IndustriesCement Industries
Cement Industries
 
Material and energy balance
Material  and energy balanceMaterial  and energy balance
Material and energy balance
 
C++ operator
C++ operatorC++ operator
C++ operator
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
 
Carbon dioxide Industries
Carbon dioxide IndustriesCarbon dioxide Industries
Carbon dioxide Industries
 
Sodium carbonate Industries
Sodium carbonate IndustriesSodium carbonate Industries
Sodium carbonate Industries
 
Chemical and process engineering by ranjit hirode
Chemical and process engineering by ranjit hirodeChemical and process engineering by ranjit hirode
Chemical and process engineering by ranjit hirode
 
Chemical engineering Introduction to Process Calculations Stoichiometry
Chemical engineering Introduction to Process Calculations StoichiometryChemical engineering Introduction to Process Calculations Stoichiometry
Chemical engineering Introduction to Process Calculations Stoichiometry
 
Material and Energy Balance
Material and Energy BalanceMaterial and Energy Balance
Material and Energy Balance
 
Rehabilitación de Pozos Petroleros
Rehabilitación de Pozos PetrolerosRehabilitación de Pozos Petroleros
Rehabilitación de Pozos Petroleros
 
Sulfuric acid Industries
Sulfuric acid IndustriesSulfuric acid Industries
Sulfuric acid Industries
 
Introduction to Chemical Engineering
Introduction to Chemical EngineeringIntroduction to Chemical Engineering
Introduction to Chemical Engineering
 
Process design for chemical engineers
Process design for chemical engineersProcess design for chemical engineers
Process design for chemical engineers
 
Concept Of C++ Data Types
Concept Of C++ Data TypesConcept Of C++ Data Types
Concept Of C++ Data Types
 
Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 

Similar to 18 dec pointers and scope resolution operator

2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2Warui Maina
 
C++ Pointers with Examples.docx
C++ Pointers with Examples.docxC++ Pointers with Examples.docx
C++ Pointers with Examples.docxJoeyDelaCruz22
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structurelodhran-hayat
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloadingankush_kumar
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndEdward Chen
 
Bca 2nd sem u-5 files & pointers
Bca 2nd sem u-5 files & pointersBca 2nd sem u-5 files & pointers
Bca 2nd sem u-5 files & pointersRai University
 
Mca 2nd sem u-5 files & pointers
Mca 2nd  sem u-5 files & pointersMca 2nd  sem u-5 files & pointers
Mca 2nd sem u-5 files & pointersRai University
 
C++ Course - Lesson 3
C++ Course - Lesson 3C++ Course - Lesson 3
C++ Course - Lesson 3Mohamed Ahmed
 
Namespace--defining same identifiers again
Namespace--defining same identifiers againNamespace--defining same identifiers again
Namespace--defining same identifiers againAjay Chimmani
 
c++ pointers by Amir Hamza Khan (SZABISTIAN)
c++ pointers by Amir Hamza Khan (SZABISTIAN)c++ pointers by Amir Hamza Khan (SZABISTIAN)
c++ pointers by Amir Hamza Khan (SZABISTIAN)Ameer Hamxa
 
FUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptxFUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptxDeepasCSE
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptxhara69
 
Namespace in C++ Programming Language
Namespace in C++ Programming LanguageNamespace in C++ Programming Language
Namespace in C++ Programming LanguageHimanshu Choudhary
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxShashiShash2
 

Similar to 18 dec pointers and scope resolution operator (20)

2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 
C++ Pointers with Examples.docx
C++ Pointers with Examples.docxC++ Pointers with Examples.docx
C++ Pointers with Examples.docx
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structure
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
 
Lecture 8
Lecture 8Lecture 8
Lecture 8
 
Bca 2nd sem u-5 files & pointers
Bca 2nd sem u-5 files & pointersBca 2nd sem u-5 files & pointers
Bca 2nd sem u-5 files & pointers
 
Mca 2nd sem u-5 files & pointers
Mca 2nd  sem u-5 files & pointersMca 2nd  sem u-5 files & pointers
Mca 2nd sem u-5 files & pointers
 
C++ Course - Lesson 3
C++ Course - Lesson 3C++ Course - Lesson 3
C++ Course - Lesson 3
 
Namespace--defining same identifiers again
Namespace--defining same identifiers againNamespace--defining same identifiers again
Namespace--defining same identifiers again
 
Operators
OperatorsOperators
Operators
 
c++ pointers by Amir Hamza Khan (SZABISTIAN)
c++ pointers by Amir Hamza Khan (SZABISTIAN)c++ pointers by Amir Hamza Khan (SZABISTIAN)
c++ pointers by Amir Hamza Khan (SZABISTIAN)
 
FUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptxFUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptx
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptx
 
Bc0037
Bc0037Bc0037
Bc0037
 
Namespace in C++ Programming Language
Namespace in C++ Programming LanguageNamespace in C++ Programming Language
Namespace in C++ Programming Language
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 
Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 

More from SAFFI Ud Din Ahmad

More from SAFFI Ud Din Ahmad (13)

Ammonia Industries
Ammonia IndustriesAmmonia Industries
Ammonia Industries
 
Phosphoric acid Industries
Phosphoric acid IndustriesPhosphoric acid Industries
Phosphoric acid Industries
 
Oxygen and nitrogen Industries
Oxygen and nitrogen IndustriesOxygen and nitrogen Industries
Oxygen and nitrogen Industries
 
Nitric acid Industries
Nitric acid IndustriesNitric acid Industries
Nitric acid Industries
 
Hydrogen Industries
Hydrogen IndustriesHydrogen Industries
Hydrogen Industries
 
Fertilizers Industries
Fertilizers IndustriesFertilizers Industries
Fertilizers Industries
 
Cuastic soda and Chlorine Industries
Cuastic soda and Chlorine IndustriesCuastic soda and Chlorine Industries
Cuastic soda and Chlorine Industries
 
Motion of particles in fluid (GIKI)
Motion of particles in fluid (GIKI)Motion of particles in fluid (GIKI)
Motion of particles in fluid (GIKI)
 
Size reduction (GIKI)
Size reduction (GIKI)Size reduction (GIKI)
Size reduction (GIKI)
 
Principles of Combustion (GIKI)
Principles of Combustion (GIKI)Principles of Combustion (GIKI)
Principles of Combustion (GIKI)
 
Liquid Fuels Lectures (GIKI)
Liquid Fuels Lectures (GIKI)Liquid Fuels Lectures (GIKI)
Liquid Fuels Lectures (GIKI)
 
Particle Technology Lectures GIKI
Particle Technology Lectures GIKIParticle Technology Lectures GIKI
Particle Technology Lectures GIKI
 
Fuels and Combustion Lectures (GIKI)
Fuels and Combustion Lectures (GIKI)Fuels and Combustion Lectures (GIKI)
Fuels and Combustion Lectures (GIKI)
 

18 dec pointers and scope resolution operator

  • 1. 1. C++ Scope Resolution Operator:: 2. Pointers C++ Scope Resolution Operator:: http://publib.boulder.ibm.com/infocenter/comphelp/v7v91/index.jsp?topic=% 2Fcom.ibm.vacpp7a.doc%2Flanguage%2Fref%2Fclrc05cplr175.htm The :: (scope resolution) operator is used to qualify hidden names so that you can still use them. You can use the unary scope operator if a namespace scope or global scope name is hidden by an explicit declaration of the same name in a block or class. For example: int count = 0; int main(void) { int count = 0; ::count = 1; // set global count to 1 count = 2; // set local count to 2 return 0; }  The declaration of count declared in the main() function hides the integer named count declared in global namespace scope.  The statement ::count = 1 accesses the variable named count declared in global namespace scope.  You can also use the class scope operator to qualify class names or class member names.
  • 2.  If a class member name is hidden, you can use it by qualifying it with its class name and the class scope operator. Example: The declaration of the variable X hides the class type X, but you can still use the static class member count by qualifying it with the class type X and the scope resolution operator. #include <iostream> using namespace std; class X { public: static int count; }; int X::count = 10;// define static data member int main () { int X = 0; // hides class type X // use static member of class X cout << X::count << endl; }
  • 3. C++ Scope Resolution Operator :: PURPOSE C++The :: (scope resolution) operator is used to qualify hidden names so that you can still use them. You can use the unary scope operator if a namespace scope or global scope name is hidden by an explicit declaration of the same name in a block or class. Namespaces Namespaces allow to group entities like classes, objects and functions under a name. In this way the global scope can be divided in "sub-scopes", each one with its own name. The format of namespaces is: namespace identifier { entities } Where identifier is any valid identifier and entities is the set of classes, objects and functions that are included within the namespace.
  • 4. For example: namespace myNamespace { int a, b; } In this case, the variables a and b are normal variables declared within a namespace called myNamespace. In order to access these variables from outside the myNamespace namespace we have to use the scope operator :: For example, to access the previous variables from outside [myNamespace=] we can write: general::a general::b The functionality of namespaces is especially useful in the case that there is a possibility that a global object or function uses the same identifier as another one, causing redefinition errors.
  • 5. For example: // namespaces #include <iostream> using namespace std; namespace first { int var = 5; } namespace second { double var = 3.1416; } int main () { cout << first::var << endl; cout << second::var << endl; return 0; } EXAMPLE OUTPUT: 5 3.1416 In this case, there are two global variables with the same name: var. One is defined as an int within the namespace first and the other one in defined as a double in the namespace called second. No redefinition errors happen thanks to namespaces.
  • 6. The 'using' Keyword The keyword using is used to introduce a name from a namespace into the current declarative region. For example: // using example #include <iostream> using namespace std; namespace first { int x = 5; int y = 10; } namespace second { double x = 3.1416; double y = 2.7183; } int main () { using first::x; using second::y cout << x << endl; cout << y << endl; cout << first::y << endl; cout << second::x << endl; return 0; } EXAMPLE OUTPUT: 5 2.7183 10 2.7183
  • 7. Notice how in this code, x (without any name qualifier) refers to first::x whereas y refers to second::y, exactly as our using declarations have specified. We still have access to first::y and second::x using their fully qualified names. The keyword using can also be used as a directive to introduce an entire namespace: // using example #include <iostream> using namespace std; namespace first { int x = 5; int y = 10; } namespace second { double x = 3.1416; double y = 2.7183; } int main () { using namespace first; cout << x << endl; cout << y << endl; cout << second::y << endl; cout << second::x << endl; return 0; }
  • 8. EXAMPLE OUTPUT: 5 10 3.1416 2.7183 In this case, since we have declared that we were using namespace first, all direct uses of x and y without name qualifiers were referring to their declarations in namespace first. using and using namespace have validity only in the same block in which they are stated or in the entire code if they are used directly in the global scope. For example, if we had the intention to first use the objects of one namespace and then those of another one, we could do something like:
  • 9. // using namespace example #include <iostream> using namespace std; namespace first { int x = 5; } namespace second { double x = 3.1416; } int main () { // Here are two blocks { using namespace first; cout << x << endl; } { using namespace second; cout << x << endl; } return 0; } EXAMPLE OUTPUT: 5 3.1416
  • 10. What Are Pointers? Reference: http://www.tutorialspoint.com/cplusplus/cpp_pointers.htm  C++ pointers are easy and fun to learn.  Some C++ tasks are performed more easily with pointers, and  other C++ tasks, such as dynamic memory allocation, cannot be performed without them. As you know every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator which denotes an address in memory. Consider the following which will print the address of the variables defined:#include <iostream> using namespace std; int main () { int var1; char var2[10]; cout << "Address of var1 variable: "; cout << &var1 << endl; cout << "Address of var2 variable: "; cout << &var2 << endl; return 0; } When the above code is compiled and executed, it produces result something as follows: Address of var1 variable: 0xbfebd5c0 Address of var2 variable: 0xbfebd5b6
  • 11. What Are Pointers?  A pointer is a variable whose value is the address of another variable.  Like any variable or constant, you must declare a pointer before you can work with it.  The general form of a pointer variable declaration is: type *variablename; Here, type is the pointer's base type; it must be a valid C++ type and variablename is the name of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration: int *ip; // pointer to an integer double *dp; // pointer to a double float *fp; // pointer to a float char *ch // pointer to character The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.
  • 12. There are few important operations Using Pointers in C++: Which we will do with the pointers very frequently: (a) We define pointer variables (b) Assign the address of a variable to a pointer and (c) Finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations: #include <iostream> using namespace std; int main () { int var = 20; // actual variable declaration. int *ip; // pointer variable ip = &var; // store address of var in pointer variable cout << "Value of var variable: "; cout << var << endl; // print the address stored in ip pointer variable cout << "Address stored in ip variable: "; cout << ip << endl; // access the value at the address available in pointer cout << "Value of *ip variable: "; cout << *ip << endl; return 0; }
  • 13. When the above code is compiled and executed, it produces result something as follows: Value of var variable: 20 Address stored in ip variable: 0xbfc601ac Value of *ip variable: 20 C++ Pointers in Detail: Pointers have many but easy concepts and they are very important to C++ programming. There are following few important pointer concepts which should be clear to a C++ programmer: Concept Description C++ Null Pointers C++ supports null pointer, which is a constant with a value of zero defined in several standard libraries. C++ pointer arithmetic There are four arithmetic operators that can be used on pointers: ++, --, +, - C++ pointers vs arrays There is a close relationship between pointers and arrays. Let us check how? C++ array of pointers You can define arrays to hold a number of pointers. C++ pointer to pointer C++ allows you to have pointer on a pointer and so on. Passing pointers to functions Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function. Return pointer from functions C++ allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well.
  • 14. C++ NULL Pointers  It is always a good practice to assign the pointer NULL to a pointer variable in case you do not have exact address to be assigned.  This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer.  The NULL pointer is a constant with a value of zero defined in several standard libraries, including iostream. Consider the following program: #include <iostream> using namespace std; int main () { int *ptr = NULL; cout << "The value of ptr is " << ptr ; return 0; } When the above code is compiled and executed, it produces following result: The value of ptr is 0 To check for a null pointer you can use an if statement as follows: if(ptr) // succeeds if p is not null if(!ptr) // succeeds if p is null
  • 15. C++ Pointer Arithmetics  As you understood pointer is an address which is a numeric value. Therefore, you can perform arithmetic operations on a pointer just as you can a numeric value.  There are four arithmetic operators that can be used on pointers: ++, --, +, and - ptr++  the ptr will point to the location 1004 because each time ptr is incremented, it will point to the next integer .  This operation will move the pointer to next memory location without impacting actual value at the memory location.  If ptr points to a character whose address is 1000, then above operation will point to the location 1001 because next character will be available at 1001.
  • 16. Incrementing a Pointer:  We prefer using a pointer in our program instead of an array because the variable pointer can be incremented, unlike the array name which cannot be incremented because it is a constant pointer.  The following program increments the variable pointer to access each succeeding element of the array: #include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr; // let us have array address in pointer. ptr = var; for (int i = 0; i < MAX; i++) { cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; // point to the next location ptr++; } return 0; }
  • 17. Pointers and arrays are strongly related. In fact, pointers and arrays are interchangeable in many cases. For example, a pointer that points to the beginning of an array can access that array by using either pointer arithmetic or array-style indexing. Consider the following program: #include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr; // let us have array address in pointer. ptr = var; for (int i = 0; i < MAX; i++) { cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; // point to the next location ptr++; } return 0; }
  • 18. When the above code is compiled and executed, it produces result something as follows: Address of var[0] = 0xbfa088b0 Value of var[0] = 10 Address of var[1] = 0xbfa088b4 Value of var[1] = 100 Address of var[2] = 0xbfa088b8 Value of var[2] = 200 MORE EXAMPLES #include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr[MAX]; for (int i = 0; i < MAX; i++) { ptr[i] = &var[i]; // assign the address of integer. } for (int i = 0; i < MAX; i++) { cout << "Value of var[" << i << "] = "; cout << *ptr[i] << endl; } return 0; } When the above code is compiled and executed, it produces following result: Value of var[0] = 10 Value of var[1] = 100 Value of var[2] = 200 You can also use an array of pointers to character to store a list of strings as follows: #include <iostream>
  • 19. using namespace std; const int MAX = 4; int main () { char *names[MAX] = { "Zara Ali", "Hina Ali", "Nuha Ali", "Sara Ali", }; for (int i = 0; i < MAX; i++) { cout << "Value of names[" << i << "] = "; cout << names[i] << endl; } return 0; } When the above code is compiled and executed, it produces following result: Value of names[0] = Zara Ali Value of names[1] = Hina Ali Value of names[2] = Nuha Ali Value of names[3] = Sara Ali