Question

In: Computer Science

// note the different names for the C libraries #include <cstdio> // cstdio instead of stdio.h...

// note the different names for the C libraries
#include <cstdio>     //  cstdio   instead of stdio.h
#include <cstdlib>    //  sstdlib  instead of stdlib.h

// a simple class to explore the ideas of:
//    data members
//    access modifiers of private, public
//    keyword static
class LabExample
{
private:
    int storage;

public:
    void setStorage (int s)
    {
        storage = s;
        // this->storage = s;
    }

    int getStorage ()
    {
        // return storage;
        return this->storage;
    }

    void modStorage ()
    {
        storage = storage * 2;
    }

    static void staticMethod ( )
    {
        printf ("Inside staticMethod()\n");

        // the following would cause an error if attempted
        //printf ("The value of storage is: %d\n", storage);
    }
};


int main ( int argc, char** argv)
{
    // create two instances of the above class
    LabExample inst1, inst2;                // LINE 1

    printf ("Inside main\n");

    inst1.setStorage (5);                   // LINE 2
    inst2.setStorage (1);                   // LINE 3

    printf ("inst1 contains: %d \n", inst1.getStorage() );     // LINE 4
    printf ("inst2 contains: %d \n", inst2.getStorage() );
    inst1.modStorage();
    inst1.modStorage();
    inst2.modStorage();
    printf ("inst1 now contains: %d \n", inst1.getStorage() );
    printf ("inst2 now contains: %d \n", inst2.getStorage() ); // LINE 5

    // repeat above with pointers to the above class
    LabExample  *ptr1, *ptr2;              // LINE 6

    // Use malloc to allocte heap memory and store address in pointers
    ptr1 = (LabExample*) malloc ( sizeof (LabExample) );   // LINE 7
    ptr2 = (LabExample*) malloc ( sizeof (LabExample) );   // LINE 8

    // must use -> instead of . since these are pointers
    ptr1->setStorage (15);                                     // LINE 9
    ptr2->setStorage (11);
    printf ("ptr1 contains: %d \n", ptr1->getStorage() );
    printf ("ptr2 contains: %d \n", ptr2->getStorage() );
    ptr1->modStorage();
    ptr1->modStorage();
    ptr2->modStorage();
    printf ("ptr1 now contains: %d \n", ptr1->getStorage() );
    printf ("ptr2 now contains: %d \n", ptr2->getStorage() ); // LINE 10

    // de-allocate the pointers
    free  (ptr1);     // Use free() when allocated with malloc()   LINE 11
    free  (ptr2);     // Use free() when allocated with malloc()   LINE 12

    // call the static method
    LabExample::staticMethod();          //   LINE 13

    printf ("End of main\n");

    return 1;
}

Question 1: Describe what is occurring at LINE 2 and LINE 3.

Question 2: Look at the lines of code starting at LINE 4 and ending at LINE 5. There are no parameters in any of the method calls in this code. Where are the values that get printed?

Question 3: LINE 6 creates two class pointers. What is actually being allocated by this line? In what type of memory does this allocation occur?

Question 4: What is being allocated by the lines marked LINE 7 and LINE 8? In what type of memory does this allocation occur?

Question 5: Why does the code from LINE 9 through LINE 10 use the arrow operator while the code from LINE 2 through LINE 5 use the dot operator?

Solutions

Expert Solution

Answer and Explanation for your Questions is provided below. If you need any further clarification, feel free to ask in comments. I would really appreciate if you would let me know if the explanation provided is to your satisfaction.

Answer 1:   

inst1.setStorage (5); // LINE 2
   inst2.setStorage (1); // LINE 3

LINE1 is calling mutator function setStorage() for inst1 object. The setStorage() function sets the value of storage data member of inst1 hence  the inst1.storage=5 .

LINE2 is calling mutator function setStorage() for inst2 object. The setStorage() function sets the value of storage data member of inst2 hence  the inst2.storage=5 .

Answer 2:

printf ("inst1 contains: %d \n", inst1.getStorage() ); // LINE 4
   printf ("inst2 contains: %d \n", inst2.getStorage() );
   inst1.modStorage();
   inst1.modStorage();
   inst2.modStorage();
   printf ("inst1 now contains: %d \n", inst1.getStorage() );
   printf ("inst2 now contains: %d \n", inst2.getStorage() ); // LINE 5

printf method prints the value returned by getStorage() function of class. getStorage() is a accessor function of class. It returns the value of dat member storage. When it is called by any object, it returns the value of storage for that object. So inst1.getStorage() function returns value of inst1.storage and inst2.getStorage() returns value of inst2.storage. So output will be:---->>>

inst1 contains: 5
inst2 contains: 1
inst1 now contains: 20
inst2 now contains: 2

Answer 3:

LabExample *ptr1, *ptr2; // LINE 6

There are two pointers created. but they are not pointing to anything right now. So only the name of pointer is allocated and not the actual object to which the pointer will point to. As it is just a variable of pointer type , So it is allocated on Stack memory.

Answer 4:

   ptr1 = (LabExample*) malloc ( sizeof (LabExample) ); // LINE 7
   ptr2 = (LabExample*) malloc ( sizeof (LabExample) ); // LINE 8

LINE7 and LINE8 creates the object of type LabExample dynamically. Now the pointer ptr1 and ptr2 points to these two objects. This is a dynamic allocation hence it is allocated on Heap memory.

Answer 5:

LINE2-LINE5 are direct objects of class so they are using dot operator to access the data members but LINE9-LINE10 are pointers so they use arrow operator to access the data members. arrow operator means pointer to member. We use arrow operator for convenience otherwise ptr1->getStorage() is equivalent to (*ptr1).getStorage().



Related Solutions

Can you write the shell scripts for these C files (code in C): #include <stdio.h> #include...
Can you write the shell scripts for these C files (code in C): #include <stdio.h> #include <string.h> #include <ctype.h> int main(int argb, char *argv[]){ char ch; int upper=1; if(argb>1){ if(strcmp(argv[1],"-s")==0){ upper=1; } else if(strcmp(argv[1],"-w")==0){ upper=0; } } while((ch=(char)getchar())!=EOF){ if(upper){ printf("%c",toupper(ch)); } else{ printf("%c",tolower(ch)); } } return 0; } ======================================================== #include <stdio.h> #include <stdlib.h> int calcRange(int array[],int size){ int max=array[1]; int min=array[0]; int a=0; for(a=1;a<size;a++){ if(array[a]>max){ max=array[a]; } } for(a=1;a<size;a++){ if(array[a]<min){ min=array[a]; } } printf("%d-%d=%d\n",max,min,max-min); } int main(int arga, char **argv){...
*Answer in C program* #include <stdio.h> int main() {      FILE *fp1;      char c;     ...
*Answer in C program* #include <stdio.h> int main() {      FILE *fp1;      char c;      fp1= fopen ("C:\\myfiles\\newfile.txt", "r");      while(1)      {         c = fgetc(fp1);         if(c==EOF)             break;         else             printf("%c", c);      }      fclose(fp1);      return 0; } In the program above which statement is functioning for opening a file Write the syntax for opening a file What mode that being used in the program. Give the example from the program Referring to...
Use C language , pointer limit use //#include <stdio.h> //#include <stdlib.h> //#include <time.h> For example, I...
Use C language , pointer limit use //#include <stdio.h> //#include <stdlib.h> //#include <time.h> For example, I have random array [4,2,7,1,9,8,0]. Sort the array's index but cannot change the position of item in the array, if you copy the array to a new array, you also cannot change the item's position in array. The index now is[0,1,2,3,4,5,6] The output should be[6,3,1,0,2,5,4]
Can you translate this C code into MIPS assembly? #include <stdio.h> #include <math.h> #include <stdlib.h> double...
Can you translate this C code into MIPS assembly? #include <stdio.h> #include <math.h> #include <stdlib.h> double fact (double); void main () { int angle_in_D; double term, angle_in_R; float sine = 0; unsigned int i = 1; double sign = 1; int n = 1000; printf ("Please enter an angle (Unit: Degree): "); scanf ("%d", &angle_in_D); angle_in_R = angle_in_D * M_PI / 180.0; do { term = pow(-1,(i-1)) * pow (angle_in_R, (2*i - 1)) / fact (2*i - 1); sine =...
#include<stdio.h> #include<stdlib.h> int main() {     //Q1) Note: You can use only pointer based operations while...
#include<stdio.h> #include<stdlib.h> int main() {     //Q1) Note: You can use only pointer based operations while implementing each of the functionalities below    // zero points will be given if pointer operations are not used in implementing    // each of the operations below.    // Also, use C code only in visual studio or GCC in general.asu.edu server    /* i.) Create a 2 - D array of integers using pointers (use dynamic memory allocation).            Assume that...
construct c program flow chart #include <stdio.h> #include <math.h> #include <string.h> #define num 6 #define b...
construct c program flow chart #include <stdio.h> #include <math.h> #include <string.h> #define num 6 #define b 6 #define t 6 double bmical(double w, double h){ double o; double bmi; o = pow(h,2); bmi = w/o; return bmi; } double maxheartrate(int num1, int age){ double mhr; mhr = num1 - age; return mhr; } double heartratereserve(double mhr, double rhr){ double hrr; hrr = mhr - rhr; return hrr; } double minrange(int hrr, int rhr){ double mirt; mirt = (hrr * 0.7)...
Include<stdio.h> In C program Write a program that prompts the user to enter an integer value....
Include<stdio.h> In C program Write a program that prompts the user to enter an integer value. The program should then output a message saying whether the number is positive, negative, or zero.
#include <stdio.h> int main() {      FILE *fp1;      char c;      fp1= fopen ("C:\\myfiles\\newfile.txt", "r");...
#include <stdio.h> int main() {      FILE *fp1;      char c;      fp1= fopen ("C:\\myfiles\\newfile.txt", "r");      while(1)      {         c = fgetc(fp1);         if(c==EOF)             break;         else             printf("%c", c);      }      fclose(fp1);      return 0; } In the program above which statement is functioning for opening a file Write the syntax for opening a file What mode that being used in the program. Give the example from the program Referring to the program above what...
In C program #include<stdio.h> You found an exciting summer job for five weeks. Suppose that the...
In C program #include<stdio.h> You found an exciting summer job for five weeks. Suppose that the total tax you pay on your summer job income is 14%. After paying the taxes, you spend: You spend 10% of your net income to buy new clothes and other accessories for the next school year You 1% to buy school supplies AFTER buying clothes and school supplies, you save 25% of the remaining money For each dollar you save, your parents add $0.50...
Are my codes correct? #include <iostream> #include <string> #include <cassert> #include <cctype> #include <cstring> #include <stdio.h>...
Are my codes correct? #include <iostream> #include <string> #include <cassert> #include <cctype> #include <cstring> #include <stdio.h> #include <ctype.h> #include<fstream> int locateMinimum( const std::string array[ ], int n ){    if(n <= 0){    return -1;    }    else{    int minInd = 0;    for(int i = 0; i < n; ++i){    if(array[i] < array[minInd]){    minInd = i;    }    }    return minInd;    } } int countPunctuation( const std::string array[], int n) { int...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT