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){...
I need the following C code converted to java or C++ #include <stdio.h> #include <stdlib.h> typedef...
I need the following C code converted to java or C++ #include <stdio.h> #include <stdlib.h> typedef struct node { struct node *left; struct node *right; long data; long leftSize; } node; void btreeInsert(node *new, node **rootptr) { node *parent = NULL, *cursor; /* Find parent */ cursor = *rootptr; while (cursor != NULL) { parent = cursor; if (new->data < cursor->data) { cursor->leftSize += 1; cursor = cursor->left; } else { cursor = cursor->right; } } /* Insert node below...
I NEED THIS CODE FOR C++ USING MONITORS PLEASE #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include...
I NEED THIS CODE FOR C++ USING MONITORS PLEASE #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #define THREADS 10 // Number of Thread //bridge declared with array of character and integer value void Bridge(char array[], int value); // Global Variable int North = 1; //For North Number int South = 1; //For South Number pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; // Setting Up MUTEX for lock //Thread for North farmer void NorthFarmer(){ pthread_mutex_lock(&mutex1); char array[5] = "North"; // North printf("%s Tunbridge...
*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 =...
Complete the task below C++ This header file declares the Comp315Array Class **************************/ //Include the libraries...
Complete the task below C++ This header file declares the Comp315Array Class **************************/ //Include the libraries #include <iostream> //Allow the use of cin and cout //Declare namespace std for using cin and cout using namespace std; //Class declaration class Comp315Array{ //Public members public: /**************** Default Constructor Task: assign 0 to the array size *********/ Comp315Array(); /**************** Constructor Task: Define an int array of size n *********/ Comp315Array(int n); /***************** getSize method Task: return the array size ******************/ int getSize(); /*****************...
#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.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT