C++ Classes and Objects

1. Describe storage classes in CPP.

There are different storage classes available in CPP. A storage class defines the scope and life-time of variables.

Following are the storage classes in CPP
  • auto
  • register
  • static
  • extern
  • mutable
1. auto storage class

By default, all local variables are auto in nature. It applies to local variables only and its scope is only inside the function in which it is declared and it dies as soon as the function execution is over. If you do not initialize auto variables, it will contain garbage value. You can also create these type of variables by using auto keyword. The memory space for local auto variable is allocated on the stack.
intvar; // by default, storage class is auto
autointvar; // Explicitly create auto variable.

2. register storage class

The register storage class is used to define local variables. Keyword register is used for declaring register variables. Register variables are similar to automatic variable and exist inside function body only but these variables store inprocessor's register rather than memory (RAM), if available. Accessing data from register variable is much faster than primary memory. It speeds up the execution of program. This class is useful when you want to refer a variable frequently.

Important things about register variable:
  • You cannot use register keyword for global variables.
  • You can declare local variable as register variables and to the formal parameters in a function.
  • You cannot take address of a register variable.
Example
classstorageTest
{
public:
     voidgetInfo()
     {
          intlocVar = 100; //---------------------- by default locVar is auto.
          registerintregVar = 200; //----------------------- register variable.
          cout<<"locVar=: "<<locVar<<endl;
          cout<<"regVar=: "<<regVar<<endl;
     }
};
void main()
{
     storageTestobj;
     obj.getInfo();
     getch();
}

3. static storage class
  • Static variables are initialized only once, at the beginning of program execution.
  • A static variable remains in memory until the end of program.
  • If you declare a data member as a static in the class, then one copy of the member is shared by all instances of the class.
  • Class, function, constructor, and variable can be declared as static.
  • Static members exist as members of the class, not as an instance of object of the class.
  • this keyword is not available in a static member function.
  • When you declare a data member within a class, you must provide a definition outside the class. You can do it by again declaring the static variable using the scope resolution operator.
  • IntstaticTest : : count;
  • Static function can access only static data members.
  • Non static function can access both static as well as non-static data members.
Example
classstaticTest
{
public:
     void counter()
     {
          staticint count = 0;
          cout<< count++;
     }
};
void main()
{
     staticTest obj1;
     staticTest obj2;
     for(int i=0;i<3;i++)
     {
          obj1.counter();
          cout<<" ";
     }
     cout<<endl;
     for(int i=0; i<3; i++)
     {
          obj2.counter();
          cout<<" ";
     }
}

When you run the above code, the output will be

0 1 2
3 4 5

If you set count variable as non-static then output will be

0 0 0
0 0 0

static storage class

4. extern storage class

If you want to share a global variable or function between two files, then declare that variable or function as extern.extern keyword tells the compiler that the variable or function is defined somewhere else or in some other file. Variables of extern storage class have a global scope. That’s why an extern variable can be shared across multiple files.

extern storage class

5. mutable storage class

Objects of class declared as const cannot modify their data members. In many situations it is necessary to modify a particular data member, even though the object of class is declared as const. To solve this problem, mutable keyword can be used on such data members. Using mutable keyword, data members of const objects can be modified to any new value.

Properties of mutable storage class
  • mutable is applicable only to data members and not to local variables.
  • static data member cannot be mutable.
  • constdata member cannot be mutable.
Example
classMutableTest
{
public:
     int x;
     mutableint y;
     MutableTest()
     {
          x = 10;
          y = 20;
     }
};
int main()
{
     constMutableTestobj;
     // obj.x=100; not possible, it will give error.
     obj.y = 30;
     cout<<obj.y<<endl;
     return 0;
}

In the above example, object of Mutable Test class is specified as const but you can modify the data member y, because y is declared as mutable. If you try to modify the value of data member x, and run the program, it will give you error because it is not mutable.

2. What is the difference between data member and variable?

A member variable or data member is a variable that belongs to an object, whereas a local variable belongs to the current scope (variables inside a function).
classMyClass
{
     int a;
     int b; //Data member
public:
     void show()
     {
          int x = 10; // local variable
          cout<<"x=:"<<x;
     }
};
void main()
{
     MyClassobj;
     obj.show();
}

At the time of creation of class, we can declare class member variables. These variables are called data members of that class. In the above given example, MyClass has two member variables, a & b. When we create an object instance of MyClass it will still have two member variables, int a and int b.

On the other hand, if we declare variables inside a function, then these variables are simply called and you cannot directly use these variables outside the function.

For example: We have created a show() function in MyClass. Variable x is declared inside show function and it is simple called as variable or local variable. It is not associated with object.

3. Write output with explanation.

constint size = 5;
void print (int * ptr)
{
     cout<<ptr [0];
}
void print (intptr [ ])
{
     cout<<ptr [0];
}
void main ()
{
     int a [size] = {1,2,3,4,5};
     int *b = newint (size);
     print (a);
     print (b);
}

Description:

The above program will give the error. In this program, there are two print functions which have the parameter int * ptr and intptr [ ]. Both the parameters have the same meaning. That’s why it will give the error redefinition of print function or print (int *) have already body.

4. What will be the output of the following program?

publicclass A
{
     int x = 4;
};
privateclass B :: class A
{
     int x=20;
     cout<<"x="<<x;
}

Description: The above program will generate error. In cpp we cannot write access specifiers as above in the program.

5. Design a class Degree and Fahrenheit to store temperature in degree and Fahrenheit. Both the classes should have member functions. So that you should be able to write statement like d1 = f1 and f1 = d1 through c++ main where d1 is object of degree class and f1 is object of Fahrenheit class.

Solution:
class Degree
{
     int deg, fah;
public:
     Degree(int temp)
     {
          deg = temp;
     }
     void showTemp()
     {
          //°F = °C x 9/5 + 32 ---------------------- Formula
          fah = 1.8 * deg + 32;
          cout<<"\n Temprature in degree = "<<deg<<" and temperature in Fahrenheit ="<<fah<<endl;
     }
};
class Fahrenheit
{
     int deg, fah;
public:
     Fahrenheit(int temp)
     {
          fah = temp;
     }
     void showTemp()
     {
          //°C = (°F - 32) x 5/9 ------------------------ Formula
          deg = (fah - 32) * 5/9;
          cout<<"\n Temprature in degree = "<<deg<<" and temperature in Fahrenheit ="<<fah<<endl;
     }
};
void main (void)
{
     int d,f;
     cout<<"Enter the temp in degree"<<endl;
     cin>>d;
     cout<<"Enter the temp in Fahrenheit"<<endl;
     cin>>f;
     Degree d1(d);
     Fahrenheit f1(f);
     d1.showTemp();
     f1.showTemp();
}

6. What will be the output of following program?

class Test
{
     staticint i;
     int j;
};
int Test :: i;
void main()
{
     cout<<sizeof(Test);
}

Output: 2
Description:
  • In the above program, there are two variables 'i' and 'j'. Variable 'i' is static, so it is not related with instance of object.
  • In 16 bit compiler sizeof (Test) will give output as 2.

7. Write output with explanation.

class MCA
{
public:
     int a;
private:
     int b;
protected:
     int c;
};
void main()
{
     MCA M;
     cout<<M.a<<M.b<<M.c;
}

Description:

The above program will give the compile time error and will not execute. Data member ‘int b’ and ‘ int c’ are declared as private and protected respectively, so you cannot access these variables outside the class.

8. Write output with explanation.

void main()
{
     char s[] = "PROGRAM";
     int i;
     for(i=0; s[i]; i++)
     cout<<"\n"<<s[i++]<<*(s+i);
}

Description:
The above program will print as follows:

PR // s[0] << s[1]
OG // s[2] << s[3]
RA // s[4] << s[5]
M // s[6] << s[7] There is no s[7], so it will print garbage value.

And after printing M, it will print some garbage value. When i=0, then s[i++] will print 'P', increment variable 'i' by one and *(s+i) will print 'R' this will continue till the end of array. After printing 'M' there will be no element int array, stll *(s+i); wants to print some data, so it will print some garbage value.