chapter-5-pointer in c++

68
Prof.Manoj S.Kavedia (9860174297)([email protected]) Introduction In c++ a pointer is a variable that points to or references a memory location in which data is stored. Each memory cell in the computer has an address that can be used to access that location so a pointer variable points to a memory location we can access and change the contents of this memory location via the pointer. Basic of Pointers Q1.What is Pointer? How pointer is declared? Ans.A pointer is a variable that contains the memory location of another variable. In c++ a pointer is a variable that points to or references a memory location in which data is stored. Each memory cell in the computer has an address that can be used to access that location so a pointer variable points to a memory location we can access and change the contents of this memory location via the pointer. Programmer start by specifying the type of data stored in the location identified by the pointer. The asterisk(*) tells the compiler that you are creating a pointer variable. Finally programmer give the name of the variable. type * variable name Example int *ptr; float *string; Q2.Describe the concept of Pointers Ans. Computer memory is sequential collection of storage cells as shown in figure. Each cell is commonly known as byte and has a number called as address associated with it. Typically the addresses are numbered sequentially starting from zero. The last address depends upon the memory size. A computer having 64KB memory will have its last address as 65535. Memory Cell Address 5 5 Pointer in C++ Pointer in C++ Syllabus Concepts of pointer (Pointer declaration, pointer operator, address operator, pointer expressions, and pointer arithmetic), Pointers & functions (Call by value, call by reference, pointer to functions, passing function to another function), Pointers in arrays (Searching, insertion & deletion),Pointers to string (Searching, finding length, comparison, concatenation, reverse), Pointers & objects (Pointers to objects, this pointer, and pointer to derived classes). 1

Upload: jaikumarguwalani

Post on 03-Oct-2015

23 views

Category:

Documents


6 download

DESCRIPTION

Pointers in c++

TRANSCRIPT

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Introduction In c++ a pointer is a variable that points to or references a memory location in

    which data is stored. Each memory cell in the computer has an address that can be used to access that location so a pointer variable points to a memory location we can access and change the contents of this memory location via the pointer.

    Basic of Pointers

    Q1.What is Pointer? How pointer is declared?Ans.A pointer is a variable that contains the memory location of another variable. In c++ a pointer is a variable that points to or references a memory location in which data is stored. Each memory cell in the computer has an address that can be used to access that location so a pointer variable points to a memory location we can access and change the contents of this memory location via the pointer.

    Programmer start by specifying the type of data stored in the location identified by the pointer. The asterisk(*) tells the compiler that you are creating a pointer variable. Finally programmer give the name of the variable.

    type * variable name

    Example

    int *ptr; float *string;

    Q2.Describe the concept of PointersAns. Computer memory is sequential collection of storage cells as shown in figure. Each cell is commonly known as byte and has a number called as address associated with it. Typically the addresses are numbered sequentially starting from zero. The last address depends upon the memory size. A computer having 64KB memory will have its last address as 65535.

    Memory Cell Address

    55 Pointer in C++Pointer in C++SyllabusConcepts of pointer (Pointer declaration, pointer operator, address operator, pointer expressions, and pointer arithmetic), Pointers & functions (Call by value, call by reference, pointer to functions, passing function to another function), Pointers in arrays (Searching, insertion & deletion),Pointers to string (Searching, finding length, comparison, concatenation, reverse), Pointers & objects (Pointers to objects, this pointer, and pointer to derived classes).

    1

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    123.....

    65535

    Fig. Memory RepresentationWhenever we declare variable, the system allocates it somewhere in the memory. An appropriate location holds the value of variable. Since every byte has a unique address number, this location will have its own address number. Consider the following statement:

    int quantity=150;

    This statement instructs the system complier system to find a location for integer variable quantity and store value 150 in that location. Let us assume that the system has chosen the address location 4096 for quantity, so it will be visualized as:

    Quantity Variable150 Value 4096 Address

    During the execution of program computer always associates the name quantity with address 4096. We may have access to the value 150 by using either the name quantity or the address 4096. Since memory addresses are simply numbers they can be assigned to some variables which can be stored in memory like any other variables. Such variables that hold memory addresses are called as pointer variables the pointer variable is nothing but a variable that contains an address which is location of another variable in memory.

    Q3.State the use of Address operator Ans.Once we declare a pointer variable we must point it to something we can do this by assigning to the pointer the address of the variable you want to point as in the following example:

    Ptr = #

    This places the address where num is stores into the variable ptr. If num is stored in memory 21260 address then the variable ptr has the value 21260.

    /* A program to illustrate pointer declaration*/ #include#include

    2

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    void main() {

    int *ptr; int sum; sum=45; *ptr=sum; cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    float *x;

    It declares x as pointer variable a floating point type.

    InitializationThe process of assigning the address of a variable to a pointer variable is known

    as initialization. For example:

    int *p;int x = 10;p = &x;

    Pointer declaration Pointer variables are declared similar to normal variable except for addition of

    unary * operator. The symbol can appear anywhere between the data type name and the pointer variable name such as,

    int *p;

    other way of declarationsint *p, x, *q;

    Q6. Write a simple program for accessing the data through pointervariable.orQ6.How to Access variable using pointerAns.Once a pointer has been assigned address of a variable, the value of that variable can be accessed using the pointer. This is done by using unary operator * (asterisk) usually known as indirection operator, dereferencing operator or contain of operator. For example:

    int marks,*p,n;marks=79;p=&marks;n=*p;

    The first line declares marks and n as integer variables and p as apointer variable pointing to an integer.

    The second line assigns value 79 to variable marks and The third line assigns address of variable marks to pointer p. The fourth line contains indirection operator *. When * is placed before a pointer variable in an expression, the pointer returns value

    of the variable of pointer. In above case *p returns value of variable marks because p contains the address of marks. The * can be remembered as value at address. Thus value of n would be 79.

    p=&marks;n=*p;is equivalent to:n=*&marks;

    4

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Q7. Explain the concept of pointers arithmetic operations with examples.Or Q7.Describe the Pointers ArithmeticAns.1. Like other variables pointer variables can be used in arithmetic operations. Example:

    int *p, x=10;p = &x;*p=*p+5;

    This statement with add the value 5 in the value pointed by p.2. Integer pointers are incremented or decremented in the multiples of 2. Similarly character by 1, float by 4 and long pointers by 8 etc.

    p++; /* valid */

    Fig.Example of Pointer

    3. We cannot add or subtract one pointer from another. Example:int *p1, *p2;p1 = p1 + p2; /* invalid */

    4. We can add or subtract the constant from pointer variable. In this case value of pointer is incremented or decremented by the scaling factor of respective data type. Example:

    p = p + 2; /* valid */

    Multiplication and Division on pointers1. The value stored at pointers Address can be added or subtracted by any constant value. Example:

    *p = *p * 4; /* valid */2. We cannot use two pointers for multiplication or division. That is,

    x = x * y;x = x / y;

    is not allowed.3. We cannot multiply or divide a pointer by constant. Example:

    p = p * 4; /* invalid */p = p / 2; /* invalid */

    5

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Q8.Program to illustrate the pointer expression and pointer arithmetic Ans.#include #includevoid main() {

    int ptr1,ptr2; int a,b,x,y,z; a=30;b=6; ptr1=&a; ptr2=&b; x=*ptr1+ *ptr2 6; y=6*- *ptr1/ *ptr2 +30; cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    4. The use of pointer arrays to character string saves the data storage space in the memory.

    5. Pointers allow C to supports dynamic memory management.6. They provide an efficient tool for manipulating dynamic data structures such as

    structures, link lists, quos, stacks, trees and graphs.7. Pointers reduce the complexity and length of the program.8. Pointers increase the execution speed and thus reduce the program execution

    time. Of course the real power of C lies in the proper use of pointers.

    Q11.Describe what is VOID and NULL pointerAns. void pointers

    The void type of pointer is a special type of pointer. In C++, void represents the absence of type, so void pointers are pointers that point to a value that has no type (and thus also an undetermined length and undetermined dereference properties). This allows void pointers to point to any data type, from an integer value or a float to a string of characters. But in exchange they have a great limitation: the data pointed by them cannot be directly dereferenced (which is logical, since we have no type to dereference to), and for that reason we will always have to cast the address in the void pointer to some other pointer type that points to a concrete data type before dereferencing it.

    One of its uses may be to pass generic parameters to a function:

    // increaser#include using namespace std;

    void increase (void* data, int psize){

    if ( psize == sizeof(char) ) {

    char* pchar; pchar=(char*)data; ++(*pchar);

    } else if (psize == sizeof(int) )

    { int* pint; pint=(int*)data; ++(*pint); }

    } }int main () { char a = 'x'; int b = 1602; increase (&a,sizeof(a)); increase (&b,sizeof(b));

    7

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Suppose the base address of x is 9092 and assuming each integer requires 2 bytes the five elements are stored as shown below . . . .

    Index Value Addressx[0] 8 9092x[1] 4 9094x[2] 9 9096x[3] 6 9098x[4] 3 9100

    The name x is defined as a constant pointer pointing to the first element x[0] and therefore value of x is 9092. If we declare p as an integer pointer then we can make the pointer p to point the array x by following assignment.

    int *p;p = &x[0];

    ORp = x; // assigning address of array to pointer

    Now we can access every value of x using p++ to move from firstelement to another i. e.

    p = &x[0]; = 9092 = p = (p+0) p = &x[1]; = 9094 = p++ = (p+1)p = &x[2]; = 9096 = p++ = (p+2)p = &x[3]; = 9098 = p++ = (p+3)p = &x[4]; = 9100 = p++ = (p+4)

    Therefore x[n] = *(p+n)

    For initializing an array at run time:for(i=0;i

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    However, because strings are in fact sequences of characters, we can represent them also as plain arrays of char elements.For example, the following array:

    char jenny [20];

    is an array that can store up to 20 elements of type char. It can be represented as:

    Therefore, in this array, we can store sequences of characters up to 20 characters long. But we can also store shorter sequences. For example, jenny could store at some point in a program either the sequence "Hello" or the sequence "Manoj Kavedia", since both are shorter than 20 characters.

    Therefore, since the array of characters can store shorter sequences than its total length, a special character is used to signal the end of the valid sequence: the null character, whose literal constant can be written as '\0' (backslash, zero).

    Our array of 20 elements of type char, called jenny, can be represented storing the characters sequences "Hello" and "Manoj Kavedia" as:

    H e l l o \0

    M a n o j K a v e d i a \0

    Initialization of null-terminated character sequences Because arrays of characters are ordinary arrays they follow all their same rules. For example, if we want to initialize an array of characters with some predetermined sequence of characters we can do it just like any other array:

    char myword[] = { 'H', 'e', 'l', 'l', 'o', '\0' }; In this case we would have declared an array of 6 elements of type char initialized with the characters that form the word "Hello" plus a null character '\0' at the end.But arrays of char elements have an additional method to initialize their values: using string literals. These are specified enclosing the text to become a string literal between double quotes ("). For example:

    "the result is: "

    is a constant string literal ..11

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Double quoted strings (") are literal constants whose type is in fact a null-terminated array of characters. So string literals enclosed between double quotes always have a null character ('\0') automatically appended at the end.

    Therefore we can initialize the array of char elements called myword with a null-terminated sequence of characters by either one of these two methods:

    char myword [] = { 'H', 'e', 'l', 'l', 'o', '\0' };char myword [] = "Hello";

    In both cases the array of characters myword is declared with a size of 6 elements of type char: the 5 characters that compose the word "Hello" plus a final null character ('\0') which specifies the end of the sequence and that, in the second case, when using double quotes (") it is appended automatically. Initializing an array of characters in the moment it is being declared, and not about assigning values to them once they have already been declared. In fact because this type of null-terminated arrays of characters are regular arrays we have the same restrictions that we have with any other array, so we are not able to copy blocks of data with an assignment operation.

    Assuming mystext is a char[] variable, expressions within a source code like:mystext = "Hello";

    mystext[] = "Hello";

    would not be valid, like neither would be: mystext = { 'H', 'e', 'l', 'l', 'o', '\0' };

    The reason for this may become more comprehensible once you know a bit more about pointers, since then it will be clarified that an array is in fact a constant pointer pointing to a block of memory.

    Using null-terminated sequences of characters Null-terminated sequences of characters are the natural way of treating strings in C++, so they can be used as such in many procedures. In fact, regular string literals have this type (char[]) and can also be used in most cases. For example, cin and cout support null-terminated sequences as valid containers for sequences of characters, so they can be used directly to extract strings of characters from cin or to insert them into cout. For example:

    // null-terminated sequences of characters#include using namespace std;

    int main (){

    char question[] = "Please, enter your first name: "; char greeting[] = "Hello, "; char yourname [80]; cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    cin >> yourname; cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    e.g,

    Q17.Describe Pointers to String can be used with exampleAns.Strings are created like character array. Therefore, they are declared and initialized as:

    char city[10] = Mumbai;

    M u m b a i \0 \0 \0 \0

    Compiler automatically inserts NULL character \0 at the end of a string. C supports an alternative method to create strings using pointer variables of type char. Such as,

    char *city = Mumbai;

    M u m b a i \0

    This creates a string and then stores its address in the pointer variable city. This pointer variable now points to the first character of the string. That is, the statements:

    Cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Example : Program to input the string and print it in reverse order

    char *str;int len = 0;coutstr;for( ;str!=\0;str++);

    str--;for( ;len>0;len--,str--)

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    name[1] Australianame[2] Newzeland

    This declares declaration allocates only 25 bytes of memory to storethe string. Following statement will print the strings on the screen:

    for(i=0;i

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    cin>>sentence ;i = 0 ;for (i=0 ; i

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    #include #include #includevoid concatenate (char str1[40],char str2[40]) ;

    void main (){ char str1[60] , str2[40] ; coutstr1 ; coutstr2 ; concatenate (str1,str2) ; cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    coutstr1; coutstr2; count = compare (i,str1,str2); if ( (str1[count] == '\0')&&(str2[count]=='\0'))

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Strings are characters arrays and here last element is \0 arrays and pointers to char arrays can be used to perform a number of string functions.

    Dynamic Memory allocationQ26.State Disadvantages of array or static allocationAns. Declaring an array with a fixed size like

    int arr[1000];

    has two typical problems:

    Exceeding maximum. Choosing a real maximum is often impossible because the programmer has no control over the size of the data sets the user is interested in. Erroneous assumptions that a maximum will never be exceeded are the source of many programming bugs. Declaring very large arrays can be extremely wasteful of memory, and if there are many such arrays, may prevent the program from running in some systems.

    No expansion. Using a small size may be more efficient for the typical data set, but prevents the program from running with larger data sets. If array limits are not checked, large data sets will run over the end of an array with disastrous consequences. Fixed size arrays can not expand as needed.

    These problems can be avoided by dynamically allocating an array of the right size, or reallocating an array when it needs to expand. Both of these are done by declaring an array as a pointer and using the new operator to allocate memory, and delete to free memory that is no longer needed.

    Q27.List the memory management operators used in c++? Ans.There are two types of memory management operators in C++

    new delete These two memory management operators are used for allocating and freeing memory

    blocks in efficient and convenient ways

    Q28.Describe new operator for dynamic memory managementAns. The new operator in C++ is used for dynamic storage allocation. This operator can be used to create object of any type.

    General syntax of new operator in C++ The general syntax of new operator in C++ is as follows

    pointer variable = new datatype;

    In the above statement, new is a keyword and the pointer variable is a variable of type datatype.

    Creating Variableint *a = new int;

    20

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Here the new operator allocates sufficient memory to hold the object of datatype int and returns a pointer to its starting point. The pointer variable a holds the address of memory space allocated.

    float *b = new float; Here the new operator allocates sufficient memory to hold the object of datatype

    float and returns a pointer to its starting point. The pointer variable a holds the address of memory space allocated.

    Exampleint bobby = new int[5];

    In this case, the system dynamically assigns space for five elements of type int and returns a pointer to the first element of the sequence, which is assigned to bobby. Therefore, now, bobby points to a valid block of memory with space for five elements of type int.

    The first element pointed by bobby can be accessed either with the expression bobby[0] or the expression *bobby. Both are equivalent as has been explained in the section about pointers. The second element can be accessed either with bobby[1] or *(bobby+1) and so on...

    The most important difference is that the size of an array has to be a constant value, which limits its size to what we decide at the moment of designing the program, before its execution, whereas the dynamic memory allocation allows us to assign memory during the execution of the program (runtime) using any variable or constant value as its size.

    Initializing / Assigning valueDynamic variables are never initialized by the compiler. The assignment can be

    made in either of the two ways:

    First methodint *a = new int(20);

    Here the new operator allocates sufficient memory to hold the object of datatype int and returns a pointer to its starting point. The pointer variable a holds the address of memory space allocated and initialize it to value 20;

    float *f = new float(20.20);Here the new operator allocates sufficient memory to hold the object of datatype

    float and returns a pointer to its starting point. The pointer variable a holds the address of memory space allocated and initialize it to value 20.20;

    21

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Second methodThe statement

    *a = 45;*b = 12.3;

    assign 45 to variable of type int and 12.3 is assigned to variable of type float;

    Creating ArraySingle Dimension

    New can be used to create a memory space for any data type including user defined types uch as arrys , structure and classes.The general form for

    int *p = new int[20];creates a memory space for an array of 20 integers.P[0] will refer ro first element ,P[1] to the second element and so on.

    MultiDimensionWhile creating multidimension array with new , all the sizes must be supplied.For example

    arr_ptr = new int[30][50]; // allowedarr_ptr = new int[35][55][15]; // allowedarr_ptr = new int[13][15][]; //not allowedarr_ptr = new int[][25][45]; // not allowed

    the first dimension may be a variable whose value is supplied at runtime.All other must be constant.

    Q29.Describe delete operator for dynamic memory managementAns. The delete operator in C++ is used for releasing memory space when the object is

    no longer needed. Once a new operator is used, it is efficient to use the corresponding delete operator for release of memory.

    General syntax of delete operator in C++

    The general syntax of delete operator in C++ is as follows:

    delete pointer variable;

    In the above example, delete is a keyword and the pointer variable is the pointer that points to the objects already created in the new operator.

    Exampledelete pointer;

    delete [] pointerThe first expression should be used to delete memory allocated for a single

    element, and the second one for memory allocated for arrays of elements

    Example: to understand the concept of new and delete memory management operator in C++:

    #include void main()

    22

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    { //Allocates using new operator memory space in memory for storing a // integer datatype int *a= new a; *a=100; cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Ans. #include #include using namespace std;

    int main (){

    int i,n; int * p; cout > i; p= new int[i]; if (p == 0)

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    { int length ; line = new line[40]; cout line ; length = calculate_length ( ) ; cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Q35.Write program to reverse string using character pointer Ans./* Program to perform Reversal of String */#include #include #include

    void main ( ) {

    int count , i ;char *line , *reverse ;line = new line[40];reverse = new reverse[40];coutline ;count = 0 ;while (*(line+count) != '\0')

    count++ ;count-- ;for(i=0 ; i= 0)

    {*(reverse+count) = *(line+i) ;count-- ;i++ ;

    }cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    coutstr2 ; concatenate (str1,str2) ; cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Pointer and Function

    Q40.Describe the concept of pointer to function and demonstrate with exampleAns. In c++ class can be defined as follows

    class MyClass{

    private: int m_Num; char m_Char;public: void getdata (int no , char ch); void putdata();

    };Whose variable can be defined as follows

    MyClass Things;Even we can define pointer in same as normal variable is declared

    MyClass *Things;

    Object to pointer are useful in creating object at run time. We can also use an object pointer to access the public member of object.Consider a class MyClass which as defined as below

    class MyClass{private: int m_Num; char m_Char;public: void getdata (int no , char ch);

    { m_Num = no;m_Char = ch;

    } void putdata()

    {cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Things.putdata();

    Same members can be accessed using pointer as follows , only difference is instead of Dot operator (.) we have to use arrow operator(->)

    PtrThings->getdata(143,P);PtrThings->putdata();

    We can also create the object using pointer and new operator as followsMyClass *ptrThings = new MyClass();

    Statement with new is used to allocate memory for the data member for the data member in the object structure and assign the address of the memory space to ptrThings.This variable can access the member function way as show

    PtrThings->getdata(143,A);PtrThings->putdata();

    Pointer and Functions

    Q41.Describe call by value an call by reference technique of argument passing to functionAns.When an array is passed as function argument only the address of first element of the array is passed but not the actual value of array elements.

    When we pass address to a function the parameters receiving the address should be pointers. The process of calling a function using pointers is called as call by reference. In general when we call a function is called as call by value.

    Call by ValueExample:

    change(int x){

    x=x+10;}

    void main(){

    int a=5;change(a); //call by valuecout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Call By Referencechange(int *x){

    *x=*x+10;}main(){

    int a+5;change(&a); // call by referenceprintf(%d,a);

    }When the function change() is called, the address of variable a (not the value) is passed into the function change(). Inside change(), variable x is declared as a pointer. Therefore x will contain the address of variable a.The statement:

    *x = *x + 10;

    means add 10 to the value stored at address of a that is x. Since x represents the address of a, value of a is changed from 5 to 15. Therefore call by reference provides mechanism by which the function can change the stored value in the calling function. This mechanism is also known as call by address or pass by pointers. Example:

    void swap(int *x, int *y) {

    int t;t = *x;*x = *y;*y = t;

    }void main()

    {int a = 5, b = 10;swap(&a, &b);cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    copy(b, a); //call by referencefor(i=0;i

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Q43.Describe what is call by reference value with example Ans.When we pass address to a function the parameters receiving the address should be pointers. The process of calling a function by using pointers to pass the address of the variable is known as call by reference. The function which is called by reference can change the values of the variable used in the call.

    /* example of call by reference*/ #include #includevoid main() {

    int x,y; x=20; y=30; cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Call:Change(a);

    Call:Change(&a);

    this pointer

    Q45.What is this pointer ? Describe this pointer with exampleAns.The this pointer is used as a pointer to the class object instance by the member function. The address of the class instance is passed as an implicit parameter to the member functions

    The keyword this identifies a special type of pointer. Suppose that you create an object named x of class A, and class A has a nonstatic member function f(). If you call the function x.f(), the keyword this in the body of f() stores the address of x. You cannot declare the this pointer or make assignments to it.

    A static member function does not have a this pointer.This is unique pointer that is automatically passed to member function when it is called.This pointer acts as an implicit argument to all the functions. An object's this pointer is not part of the object itself; it is not reflected in the result of a sizeof statement on the object. Instead, when a nonstatic member function is called for an object, the address of the object is passed by the compiler as a hidden argument to the function

    important points about this pointer: this pointer stores the address of the class instance, to enable pointer access of

    the members to the member functions of the class. this pointer is not counted for calculating the size of the object. this pointers are not accessible for static member functions. this pointers are not modifiable.

    Example of this pointerEvery class member function has a hidden parameter: the this pointer. this

    points to the individual object. Therefore, in each call to GetAge() or SetAge(), the this pointer for the object is included as a hidden parameter.

    It is possible to use the this pointer explicitly, as program below illustrates.Using the this pointer.

    // // Using the this pointer

    #include

    class Rectangle { public:

    Rectangle(); ~Rectangle(); void SetLength(int length)

    {

    35

    http://www.codersource.net/cpp_tutorial_class.html

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    this->itsLength = length; }

    int GetLength() const {

    return this->itsLength; }

    void SetWidth(int width) {

    itsWidth = width; }

    int GetWidth() const {

    return itsWidth; }

    private: int itsLength; int itsWidth;

    };

    Rectangle::Rectangle() {

    itsWidth = 5; itsLength = 10; }

    Rectangle::~Rectangle() { }

    int main() {

    Rectangle theRect; cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    GetWidth accessors do not. There is no difference in their behavior, although the syntax is easier to understand.

    If that were all there was to the this pointer, there would be little point in bothering you with it. The this pointer, however, is a pointer; it stores the memory address of an object. As such, it can be a powerful tool.

    We donot have to worry about creating or deleting the this pointer. The compiler takes care of that.

    Pointer to ObjectQ46.Describe the concept of pointer to objectAns.A pointer is a variable which holds the memory address of another variable of nay basic data type such as int , float , or sometime an array.A pointer can be used to hold the address of the structure variable too.The pointer variable is very much used to construct complex data base using the data structures such as linked list , double linked list and binary trees.ExampleClass sample

    {private :

    int x;float y;char s;

    public :void getdata();void display();

    };

    sample *ptr;where ptr is pointer variable that holds the address of the class object sample and consist of the three data member such as int x , float y , and char s and also holds member function such as getdata() and display();

    The pointer to an object of class viable will be accessed and processed in on of the following ways

    (*object_name).member_name = variable ;The parenthses are essential since the member of the class period(.) has a higher

    precedence over the indirection operator(*). Or the pointer to the member of a class can be expressed using (-) followed by greater than sign(>).This is also called as arrow(->) operator.

    Object_name->membername = variable;Object_name->memberfunction();

    Following are valid declaration of using pointer to the member of class.

    Example// Pointer to objectclass student

    { private:

    long int rollno;37

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    int age;char gender;float height;float weight;

    public:void getinfo()

    {cout > rollno;cout > age;cout > gender;cout > Height =;cout > weight;

    }

    void disinfo(){

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Content of clasRoll no = 95143Age = 39Gender = MHeight = 123Weight = 84

    Q47. Write program to assign some value to the member of class objects using an indirection operatorAns. class student

    { private:

    long int rollno;int age;char gender;float height;float weight;

    public:void getinfo()

    {cout > rollno;cout > age;cout > gender;cout > Height =;cout > weight;

    }

    void disinfo(){

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    { width = a;

    height = b;}

    int main () {

    CRectangle a, *b, *c; CRectangle * d = new CRectangle[2]; b= new CRectangle; c= &a; a.set_values (1,2); b->set_values (3,4); d->set_values (5,6); d[1].set_values (7,8); cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Hence even if C++ permits a base pointer to point any object derived from that base , the pointer cannot directly used to access all the member of the derived class.Hence the only way to access those members of derived class it to declare one more pointer to derived class.

    Example of Pointer to derived class object#include#include

    class BaseClass{

    public:int bs;void show()

    {cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    derivedClass *dpointer; // derived class pointerdpointer-> &derivedobj;dpointer->ds = 3691;cout show(); //derived pointer point derived class membergetch();

    }Output

    bpointer point to object of base classBase class Variable B = 1234

    bpointer now points to object of derived classnBase class Variable B = 2468

    dpointer point to object of derived classBase class Variable B = 2468;Dervied class Variable D =3691

    Explanationbpointer->show(); it works because bpointer is pointer to base class hence no problem or ambiguity in accessing it.

    /* bpointer->ds=3691*/ it cannot be used because base class pointer cannot access public member of derived class.

    dpointer->show(); it works because dpointer is pointer to derived class hence no problem or ambiguity in accessing it.

    Q51.Write a program to demonstrate Pointer to Derived class objectAns./* Pointers to Derived Class Objects */#include /*----------------------Class Interfaces-------------------------*/class A {

    int a1; // private data memberpublic :

    int a2; // public data member

    void set(int);void display();

    };class B : public A {

    int a3; // private data memberpublic :

    43

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    int a4; // public data member

    void set(int); // overriding functionsvoid display();

    };/*----------------------Class Implementations---------------------*/// member function definitions for class Avoid A::set(int x) {

    a1 = x; }void A::display() {

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    }

    ExplanationA base class A with one private data number a1 which can be initialised through

    the public member function set() and a2 is the public data member. There is one more public member function display() which displays the values of a1 and a2. This Program then defines the derived class B. Similarly containing one public data member a4 and private data member a3 initialised by public member function set(). Also, similar to display function of base class A, the derived class B defines a display() function which display for values of a3 and a4.

    See that initially program defines a base class pointer ant base class object and assigns the address of base class object obj1 to base class pointer base. Then through the pointer to object it invokes to initialise a1 and also initialises a2 the public member through direct assignment It then displays the values of al and a2 using public member function display().

    The program then defines a derived class pointer derived and set the address of obj2, which is a derived class object, to it. Now obj2 can invoke its own interface and initialises member a3 and a4 and can invokes its own member function set() and display() which are overriding functions. This can be seen in the third set of output values in output

    String program using pointer (new and delete operator ) class and ObjectsQ52.Write program to Find Length of string using character pointer Ans. /* Program to calculate Length of String */

    #include #include #include #include class StringLength

    {private: char *str ;

    int count;

    StringLength ( char *s){

    s = new char[strlen(s)+1];strcpy(str , s);

    }

    void calculate_length ( ){

    int count = 0 ; while (*(line+count) != '\0')

    {count++ ;

    }

    45

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    }

    void displayString(){

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    }

    void Copy_String( ){

    while (*(str+i) != '\0'){

    *(cstr+i) = *(str+i) ;i++ ;

    } *(cstr+i) = \0;

    }

    void displayString(){

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    private: char *str , *rstr;

    int count,i;

    StringReverse( char *s){

    s = new char[strlen(s)+1];strcpy(str , s);rstr = new char[strlen(s)+1];count= 0;

    }

    void Reverse_String( ){ count = 0 ;

    while (*(str+count) != '\0')count++ ;

    count-- ;for(i=0 ; i= 0)

    {*(reverse+count) = *(line+i) ;

    count-- ;i++ ;

    }

    }

    void displayString(){

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    cin>>line ;StringReverse SR1(line);SR1.Reverse_String();SR1.displayString();getch ( ) ;

    }

    Q55.Write program to concatenate string using character pointerAns./* Program to perform Concatenation of Strings */class StringConcatenate

    {private: char *str1 , *str2;

    int count,i,j;

    StringConcatenate( char *s1 , char *s2 ){

    str = new char[strlen(s1)+1];strcpy(str , s);cstr = new char[strlen(s2)+1];count= 0;

    }

    void concatenate_String (){

    i = 0 ;

    while (*(str1+i) != '\0') i++ ;

    *(str1+i) = ' ' ; i++ ;

    j = 0 ; while (*(str2+j) != '\0')

    {*(str1+i) = *(str2+j) ;i++ ;j++ ;

    }}

    void displayString(){

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    {delete str1;delete str2;

    }

    };void main ()

    { char *st1 , *st2 ; st1 = new st1[60]; st2 = new st2[40]; coutst1 ; coutst2 ; StringConcatenate SC1(st1, st2);

    SC1.concatenate () ; SC1.displayString(); getch ( ) ;}

    Q56.Write program to compare string using character pointerAns. /* Program to perform Comparisons of Two Strings */class StringCompare

    {private: char *str1 , *str2;

    int count,i,j;

    StringCompare( char *s1 , char *s2 ){

    str = new char[strlen(s1)+1];strcpy(str , s);cstr = new char[strlen(s2)+1];count= 0;

    }

    void Compare_String () {

    i = 0 ; whil e ((*(str1+i)==*(str2+i))&&(*(str1+i)!='\0')&&(*(str2)!='\0'))

    ++i ; }void displayString()

    {cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    if ( (*(str1+count) == '\0')&&(*(str2+count)=='\0'))cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Ans. :Both will return the same element of array. Consider the following example to understand it.

    # include iostream.hvoid main(){

    int myarray[]={10,20,30,40,50};cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Program-2.Two dimension array using pointers

    #include#includevoid main (){

    int a[10][10],r,c,i,j;cout&r;cout&c;

    for(i=0; i < r;i++)for(j = 0;j < c;j++)

    cin>>(*(a+i)+j);

    for(i = 0;i < r;i++){

    for(j=0;j

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    }for(i=1;i

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    cin>>&a;cout&b;

    c = p(a,b);return c;

    }

    Program-6.Factorial using Recursive function

    #include#include

    int fact(int);void main ( ){

    int n,f;clrscr( );cout&n;f = fact (n);cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    e = power (x,n);cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Ans.#include#include#includevoid main(){

    char *str , i ,len;// read the stringcoutstr;len = strlen(str);

    //print the string in reverse orderfor (i=1;i

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    swap(&c,&d);cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    #include using namespace std;

    class CRectangle { int width, height; public: void set_values (int, int); int area (void) {return (width * height);}};

    void CRectangle::set_values (int a, int b) { width = a; height = b;}

    int main () { CRectangle a, *b, *c; CRectangle * d = new CRectangle[2]; b= new CRectangle; c= &a; a.set_values (1,2); b->set_values (3,4); d->set_values (5,6); d[1].set_values (7,8); cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    void getdata ( ) {

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    acc3 . display ( ) ; acc4 . display ( ) ;acc5 . display ( ) ; int +m ; cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    case A :case e :case E :case i :case I :case o :case O :case u :case U :

    vowel++;break;

    default :consonant++;

    }

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    int function ( int a, int b , int c){ int d;

    d = a + b + c;return ( d ) ;

    }Program no -19Write C++ program to swap two numbers using call by value.Ans./* Program to illustrates passing by value */

    #include#includevoid swap (int, int) ;void main( )

    {int a = 11, b = 22;cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Program no -21Write C++ program to demonstrate function argument by value methodAns. /* Objects as Function Arguments -by value*/

    #include #includeclass Rational

    {int numerator;int denominator;

    public : void set(int, int); // prototypes declaredvoid print();void sum (Rational, Rational);

    };void Rational::set(int a, int b)

    {numerator = a;denominator = b;

    }void Rational::print()

    {cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Program no -22Write C++ program to demonstrate function argument by reference methodAns. /* Objects as Function Arguments -by reference*/

    #include #include

    class Rational{

    int numerator;int denominator;

    public : void set(int, int); // prototypes declaredvoid print();void exchange (Rational*);

    };void Rational::set(int a, int b)

    {numerator = a;denominator = b;

    }

    void Rational::print(){

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    c. Explain the role of access specifier in inheritance. Give example.d. Write a program to find the length of a string using pointers.

    Winter 2009a. Write use of this pointer. Give example.b. Write example of pointer to object.c. Distinguish between call by value and call by reference method.d. Write a program to display the string in reverse ordere. Explain command line arguments.

    Summer 2010a. What is pointer? How to declare pointer, give syntax.b. Explain the concept of this pointer.c. Write -a program to copy content of one string to another string using pointer to

    stringd. Write a program to concatenate 2 strings using pointer to string.

    68

    Introduction Q1.What is Pointer? How pointer is declared?Q3.State the use of Address operator orQ6.How to Access variable using pointerNull pointerUsing null-terminated sequences of charactersPointer to ArrayQ25.Describe the concept of Pointer to arrays with exampleQ27.List the memory management operators used in c++?

    These two memory management operators are used for allocating and freeing memory blocks in efficient and convenient waysQ28.Describe new operator for dynamic memory managementCreating ArrayWhile creating multidimension array with new , all the sizes must be supplied.Q29.Describe delete operator for dynamic memory managementAns.The delete operator in C++ is used for releasing memory space when the object is no longer needed. Once a new operator is used, it is efficient to use the corresponding delete operator for release of memory.

    Q31.List the similarities between malloc and new operatorQ42.Describe what is call by value with example Call by value Q43.Describe what is call by reference value with example important points about this pointer: