Pointers
A pointer is one of the key aspects of C++ language similar to that of C.
As we know, pointers offer a unique approach to handle data in C and
C++. We have seen some of the applications of pointers early. In this
section, we shall discuss the rudiments of pointers and special usage of
them in C++.
We know that a pointer is a derived data type that refers to
another data variable by storing the variable's memory address rather
than data.
A pointer variable defines where to get the value of a specific
data variable instead of defining actual data. Like C, a pointer variable
can also refer to (or point to) another pointer in C++. However, it often
points to a data variable. Pointers provide an alternative approach to
access other data objects.
Declaring and Initializing Pointers
We can declare a pointer variable similar to other variables in C++. Like
C, the declaration is based on the data type of the variable it points to.
The declaration of a pointer variable takes the following form:
data-type *pointer-variable;
Here pointer-variable is the name of the pointer, and the data-type
refers to one of the valid C++ data types, such as int, char, float, and so
on. The data-type is followed by an asterisk (*) symbol, which
distinguishes a pointer variable from other variables to the compiler. .
int *ptr;
Pointer to object
Objects in c++ are defined as the instance of a class. It is also
referred to as a piece of code that represents the member of its class of
variables of its class. An object can access all the members of its class.
So, we can also say a class is a collection of many objects inside it. An
object can be created many times but a class can be defined once only.
Syntax for objects in c++: The syntax of defining an object in c++
is done as given below.
Class_name object_name;
When we create an object, all the members of the class are defined
inside that particular class. These objects can access the data members
with the help of a dot(.) operator.
Advantages of using Pointer to Objects in C++.
Pointers can be used to store the memory address of a variable.
The syntax for this is as follows.
datatype *var_name;
Example In the example given below, ptr stores the address of an
integer variable. Using this pointer we can access the memory address
of that particular variable int.
int *ptr;
Using a pointer to an object in c++, we can save memory space
and we can directly manipulate the memory.
Execution becomes faster when we use pointers because a
pointer manipulates the memory address of data rather than
accessing the data.
Pointer to object in c++ is used with data structures like two-
dimensional arrays and multi-dimensional arrays.
Pointers to objects can be used for File Handling.
When we declare a pointer to the base class, then an object of the
derived class can be accessed by the base class.
Pointer to object in c++ can be used to dynamically allocate the
memory.
Pointer to object in c++ is defined as the pointer that is used for
accessing objects.
A pointer is a variable that stores the memory address of another
variable.
The types of the pointer are Null pointer, Void pointer, Wild
pointer, and Dangling pointer.
An object is defined as the instance of a class.
These objects can access the data members with the help of
a dot(.) operator.
Pointer to object in c++ helps to execute a program faster.
EXAMPLE:
#include<iostream>
using namespace std;
class Date
{
private:
short int dd, mm, yy;
public:
Date() //constrctor:
{
dd = mm = yy = 0;
}
void getdata(int i, int j, int k)
{
dd = i;
mm = j;
yy = k;
}
void putdata(void)
{
cout<<"\nData is "<<dd<<"/"<<mm<<"/"<<yy<<"\n";
}
};
int main()
{
Date D1; //simple object having type Data:
Date *dptr; //Pointer Object having type Date:
dptr = &D1;
cout<<"Initializing data members using the object, with values 19, 10,
2016"<<endl;
D1.getdata(19,10,2016);
cout<<"Printing members using the object ";
D1.putdata();
return 0;
}
Output:
Initializing data members using the object, with values 19, 10, 2016
Printing members using the object
Data is 19/10/2016
Pointer to Drived class.
We can use pointers not only to the base objects but also to the object
of the derived classes. Pointers to objects of a base class are type
compatible to the objects of a derived class.
Therefore a single pointer variable can be made to point to
objects belonging to different classes. For example if B is a base class
and D is a derived class from B, then a pointer declared as a pointer to B
can also be a pointer to D.
B base;
D derived;
B *p;
P=&base;
We can make pointer to point to the object of D.
P=&derived;
In a case a members of D has the same name as one of the members of
B, then any reference to that members by pointer will always access
the base class members.
EXAMPLE:
//Base Class Pointer derived Class Object
#include<iostream>
using namespace std;
class car //Base Class
{
public:
void start()
{
cout<<"Car Start"<<endl;
}
};
class BMW:public car //Derived Class
{
public:
void AdvanceGear()
{
cout<<"BMW Advance Gear"<<endl;
}
};
int main()
{
BMW b;
car *p=NULL;
p=&b;
p->start();
return 0;
}
Output:
Car Start
this Pointer.
C++ uses a unique keyword called this to represent an object that
invokes a member function. this is a pointer that points to the object
for which this function was called.
this pointer using for this Keyword.
This unique pointer is automatically passed to a member function
when it is called. The pointer this acts as an implicit argument to all the
member functions.
Consider the following simple example:
class ABC
{
int a;
……..
};
The private variable 'a' can be used directly inside a member
function, like a = 123; we can also use the following statement to do
the same job:
this -> a = 123;
The other argument is implicitly passed using the pointer this. one
important application of the pointer this is to return the object it points
to. For example the statement
return *this;
inside a member function will return the object that invoked the
function. This statement assumes importance when we want to
compare two or more objects inside a member function and return the
invoking object as a result.
EXAMPLE:
//Using *this pointer
#include<iostream>
using namespace std;
class Test
{
private:
int x, int y;
public: Test(int x = 0, int y = 0)
{
this->x = x;
this->y = y;
}
Test &setX(int a)
{
x = a;
return *this;
}
Test &setY(int b)
{
y = b;
return *this;
}
void print()
{
cout << "x = " << x << " y = " << y << endl;
}
};
int main()
{
Test obj1(5, 5);
obj1.setX(10);
obj1.setY(20);
obj1.print();
return 0;
} Output: x=10 y=20
Virtual Function.
o A C++ virtual function is a member function in the base class that
you redefine in a derived class. It is declared using the virtual
keyword.
o It is used to tell the compiler to perform dynamic linkage or late
binding late binding also call dynamic binding we can implicit and
indirect function call our program.
o There is a necessity to use the single pointer to refer to all the
objects of the different classes. So, we create the pointer to the
base class that refers to all the derived objects. But, when base
class pointer contains the address of the derived class object,
always executes the base class function. This issue can only be
resolved by using the 'virtual' function.
o A 'virtual' is a keyword preceding the normal declaration of a
function.
o When the function is made virtual, C++ determines which function
is to be invoked at the runtime based on the type of the object
pointed by the base class pointer.
Rules for Virtual Function.
1. The virtual functions must be members of some class.
2. They cannot be static members.
3. They are accessed by using object pointers.
4. A virtual function can be a friend of another class.
5. A virtual function in a base class must be defined, even though it
may not be used.
6. The prototypes of the base class version of a virtual function and all
the derived class versions must be identical. If two functions with the
same name have different prototypes, C++ considers them as
overloaded functions, and the virtual function mechanism is ignored.
7. We cannot have virtual constructors, but we can have virtual
destructors.
8. While a base pointer can point to any type of the derived object, the
reverse is not true. That is to say, we cannot use a pointer to a
derived class to access an object of the base type.
9. When a base pointer points to a derived class, incrementing or
decrementing it will not make it to point to the next object of the
derived class. It is incremented or decremented only relative to its
base type. Therefore, we should not use this method to move the
pointer to the next object.
10. If a virtual function is defined in the base class, it need not be
necessarily redefined in the derived class. In such cases, calls will
invoke the base function.
EXAMPLE:
#include <iostream>
using namespace std;
class A
{
public:
virtual void display()
{
cout << "Base class is invoked"<<endl;
}
};
class B:public A
{
public:
void display()
{
cout << "Derived Class is invoked"<<endl;
}
};
int main()
{
A* a; //pointer of base class
B b; //object of derived class
a = &b;
a->display(); //Late Binding occurs
} Output: Derived Class is invoked
Pure Virtual Function.
o A virtual function is not used for performing any task. It only
serves as a placeholder.
o When the function has no definition, such function is known as
"do-nothing" function.
o The "do-nothing" function is known as a pure virtual function. A
pure virtual function is a function declared in the base class that
has no definition relative to the base class.
o A class containing the pure virtual function cannot be used to
declare the objects of its own, such classes are known as abstract
base classes.
o The main objective of the base class is to provide the traits to the
derived classes and to create the base pointer used for achieving
the runtime polymorphism.
Pure virtual function can be defined as:
virtual void display() = 0;
Let's see a simple example:
#include <iostream>
using namespace std;
class Base
{
public:
virtual void show() = 0;
};
class Derived : public Base
{
public:
void show()
{
std::cout << "Derived class is derived from the base class." ;
}
};
int main()
{
Base *bptr;
//Base b;
Derived d;
bptr = &d;
bptr->show();
return 0;
}
Output:
Derived class is derived from the base class.
Runtime type identification
In C++, RTTI (Run-time type information) is a mechanism that exposes
information about an object’s data type at runtime and is available only
for the classes which have at least one virtual function.
It allows the type of an object to be determined during program
execution.
Runtime Casts
The runtime cast, which checks that the cast is valid, is the
simplest approach to ascertain the runtime type of an object using a
pointer or reference.
This is especially beneficial when we need to cast a pointer from a
base class to a derived type. When dealing with the inheritance
hierarchy of classes, the casting of an object is usually required. There
are two types of casting:
Upcasting: When a pointer or a reference of a derived class object is
treated as a base class pointer.
Downcasting: When a base class pointer or reference is converted to a
derived class pointer.
Using ‘dynamic_cast‘: In an inheritance hierarchy, it is used for
downcasting a base class pointer to a child class.
On successful casting, it returns a pointer of the converted type
and, however, it fails if we try to cast an invalid type such as an object
pointer that is not of the type of the desired subclass.
For example, dynamic_cast uses RTTI and the following program
fails with the error “cannot dynamic_cast `b’ (of type `class B*’) to type
`class D*’ (source type is not polymorphic) ” because there is no virtual
function in the base class B.
EXAMPLE:
// C++ program to demonstrate
// Run Time Type Identification successfully
// With virtual function
#include <iostream>
using namespace std;
// Initialization of base class
class B {
virtual void fun() {}
};
// Initialization of Derived class
class D : public B {
};
// Driver Code
int main()
{
B* b = new D; // Base class pointer
D* d = dynamic_cast<D*>(b); // Derived class pointer
if (d != NULL)
cout << "works";
else
cout << "cannot cast B* to D*";
return 0;
}
Output:
Works
C++ Streams
The I/O system in C++ is designed to work with a wide variety of devices
including terminals, disks, and tape drives. Although each device is very
different, the I/O system supplies an interface to the programmer that
is independent of the actual device being accessed.
This interface is known as stream.
A stream is a sequence of bytes. It acts either as source from which the
input data can be obtained or as a destination to which the output data
can be sent.
The source stream that provides data to the program is called the input
stream and the destination stream that receives output from the
program is called the output stream. In other words a program
extracts the bytes from an input stream and inserts bytes into an
output stream as illustrated in following figure.
C++ Streams Classes
What is #include in C++?
iostream stands for standard input-output stream.
#include iostream declares objects that control reading from and
writing to the standard streams.
In other words, the iostream library is an object-oriented library that
provides input and output functionality using streams.
A stream is a sequence of bytes. You can think of it as an abstraction
representing a device.
You can perform I/O operations on the device via this abstraction.
You must include iostream header file to input and output from a C++
program.
#include iostream provides the most used standard input and output
streams, cin and cout.
1. Standard Output Stream -- cout
It is an instance of the ostream class.
It produces output on the standard output device, i.e., the display
screen.
We need to use the stream insertion operator << to insert data into
the standard output stream cout, which has to be displayed on the
screen.
Syntax: cout << variable_name; OR cout << variable1 <<
variable2 << ... ;
2. Standard Input Stream -- cin
It is an instance of the istream class.
It reads input from the standard input device, i.e., the keyboard.
We need to use the stream extraction operator >> to extract data
entered using the keyboard.
Syntax: cin >> variable_name; OR cin >> variable1 >>
variable2 >> ... ;
The C++ I/O system contains a hierarchy of classes that are used to
define various streams to deal with both the console and disk files.
Theses are called stream classes.
Following figure shows hierarchy of the stream classes used for
input and output operations with the console units.
These classes are declared in the header file iostream.h. This file
should be included in
all the programs that communicate with the console unit.
The ios is the base class for istream (input stream) and ostream
(output stream) The class ios is declared as virtual base class so that
only one copy of its members are inherited by the iostream.
Unformatted and formatted I/O operations
1.Unformatted I/O operation:
The printed data with default setting by the I/O function of the
language is known as unformatted data.
It is the basic form of input/output and transfers the internal binary
representation of the data directly between memory and the file.
For example, in cin statement it asks for a number while executing. If
the user enters a decimal number, the entered number is displayed
using cout statement.
There is no need to apply any external setting, by default the I/O
function represents the number in decimal format.
in C++, we can read the input entered by a user at console using an
object cin of istream class and through this object we can access the
functions of istream class, such as - get(char *), get(void) and
getline().
In C++, we can write the output at console using an
object cout of ostream class and through this object we can access the
functions of ostream class, such as - put(), write().
Some of the most important formatted console input/output functions
are -
Functions Description
Reads a single character from the user at the console and
get(char *) assigns it to the char array in its argument, but needs
an Enter key to be pressed at the end..
Reads a single character from the user at the console, and
get()
returns it.
Reads a line of characters, entered by the user at the
getline(char* arr,
console which ends with a newline character or until the
int size)
size of .
put(char ch) Writes a single character at the console.
write(char *arr, int
Writes a number of characters in a char array to the
num)
console.
EXAMPLE:
//CHARACTER I/O WITH get() AND put()
#include <iostream>
using namespace std;
int main()
{
int count = 0;
char c;
cout << "INPUT TEXT\n";
cin.get(c);
while (c != '\n')
{
cout.put(c);
count++;
cin.get(c);
}
cout << "\nNumber of characters = " << count << "\n";
return 0;
}
PROGRAM OUTPUT
INPUT TEXT:
Object Oriented Programming
output
Object Oriented Programming
Number of characters = 27
//READING STRINGS WITH getline()
#include<iostream>
using namespace std;
int main()
{
int size = 20;
char city[20];
cout << "Enter city name: \n";
cin >> city;
cout << "City name:" << city << "\n\n";
cout << "Enter city name again: \n";
cin.getline(city, size);
cout << "City name now: " << city << "\n\n";
cout << "Enter another city name: \n";
cin.getline(city, size);
cout << "New city name: " << city << "\n\n";
return 0;}
Enter city name:
Delhi
City name: Delhi
Enter city name again:
City name now:
Enter another city name:
Chennai
New city name: Chennai
EXAMPLE:
//DISPLAYING STRINGS WITH write()
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i;
char * string1 = "c++ ";
char * string2 = "Programming";
int m = strlen(string1);
int n = strlen(string2);
for (int i=1; i < n; i++)
{
cout.write(string2,i);
cout << "\n";
}
for (i=n; i>0; i--)
{
cout.write(string2, i);
cout << "\n";
}
// concatenating strings
cout.write(string1,m) . write(string2,n);
cout << "\n";
// crossing the boundary
cout.write(string1,10);
return 0;
}
2.Formatted data I/O operations:
If the user needs to display a number in hexadecimal format, the data
is represented with the manipulators are known as formatted data.
It converts the internal binary representation of the data to ASCII
characters which are written to the output file.
It reads characters from the input file and coverts them to internal
form.
For example, cout<<hex<<13; converts decimal 13 to hexadecimal d.
Formatting is a representation of data with different settings (like
number format, field width, decimal points etc.) as per the
requirement of the user.
Formatted console input/output functions are used for performing
input/output operations at console and the resulting data is formatted
and transformed.
For more on formatted input/output functions, please read formatted
input/output functions.
Some of the most important formatted console input/output functions
are –
Functions Description
Using this function, we can specify the width of a value to
width(int width) be displayed in the output at the console.
fill(char ch)
Using this function, we can fill the unused white spaces in a
value(to be printed at the console), with a character of our
choice.
Using this function, we can set the flags, which allow us to
setf(arg1, arg2)
display a value in a particular format.
Using this function, we could clear the flag specified fixed
unsetf(char ch) by the function setf().
Using this function, we can specify the number of
precision(int
digits(num_of_digits) to the right of decimal, to be printed
num_of_digts)
in the output.
In C++, we can read the input entered by a user at console using an
object cin of istream class and we can write the output at console using
an object cout of ostream class. Through the cin and cout objects.
EXAMPLE:
#include <iostream>
using namespace std;
int main()
{
cout.setf(ios::showpos);
cout.setf(ios::scientific);
cout << 123 << " " << 123.23 << endl;
cout.precision(2); // two digits after decimal point
cout.width(10); // in a field of 10 characters
cout << 123 << " ";
cout.width(10); // set width to 10
cout << 123.23 << endl;
cout.fill('#'); // fill using #
cout.width(10); // in a field of 10 characters
cout << 123 << " ";
cout.width(10); // set width to 10
cout << 123.23;
return 0;
}
Use of Manipulators
Manipulators are special functions that can be included in the I/O
statements to alter the format parameters of a stream. Following table
shows some important manipulators functions that are frequently
used. To access manipulators, the file iomanip.h should be included in
the program.
Advantages and Purpose of Manipulators
*. It is mainly used to make up the program structure.
*. Manipulators functions are special stream function that changes
Certain format and characteristics of the input and output.
*.To carry out the operations of the manipulators <iomanip.h> must be
included.
*.Manipulators functions are specially designed to be used in
conjunction with insertion (<<) and extraction (>>) operator on
stream objects.
*.Manipulators are used to changing the format of parameters on
streams and to insert or extract certain special characters.
Standard input/output Manipulators in C++
Here is the list of standard input/output Manipulators and their
Functions in C++
1. setw (int n) – To set field width to n The setw() function is an output
manipulator that inserts whitespace between two variables. You must
enter an integer value equal to the needed space.
2.setprecision (int p) – It is an output manipulator that controls the
number of digits to display after the decimal for a floating point integer.
Make careful to include the ipmanip header in your program because
the function is defined there.
3.setfill (Char f) – To set the character to be filled The precision is fixed
to p It replaces setw(whitespaces )’s with a different character. It’s
similar to setw() in that it manipulates output, but the only parameter
required is a single character. It’s worth noting that a character is
contained in single quotes.
4.setiosflags (long l) – Format flag is set to l Generally it is used to set
different types of the flag in our program. That means when we use
setw it print the matter from Right to left but names are always print
from left to right. So for that, we use setiosflag. Setiosflag also used to
represent the sign, to represent the number scientifically and also use it
in the number system.
5.resetiosflags (long l) – Removes the flags indicated by setiosflags.
6.endl – Gives a new line The endl character introduces a new line or a
line feed. It is analogous to the “n” character in the C computer
language, and C++ supports the old line feed.
EXAMPLE:
#include<iomanip>
#include<iostream>
using namespace std;
int main()
{
cout<< setw(10) << 1 << endl;
cout<< setw(10) << 10 << endl;
cout<< setw(10) << setfill('*')<< 100 << endl;
cout<< setprecision(2) << 22/7.0 << endl;
cout<< setw(5) << setiosflags(ios::left)<<"Hello"<< endl;
cout<< setw(20) << resetiosflags(ios::right)<<"Hello"<< endl;
}