|
|
|
C++ |
|
Home >
Interview Questions >
C++
|
|
C++
Interview Questions Page 3 |
|
<<Previous Next>> |
What are storage qualifiers in
C++ ?
They are..
const
volatile
mutable
Const keyword indicates that memory once initialized, should not
be altered by a program.
volatile keyword indicates that the value in the memory location
can be altered even though nothing in the program
code modifies the contents. for example if you have a pointer to
hardware location that contains the time, where hardware changes
the value of this pointer variable and not the program. The
intent of this keyword to improve the optimization ability of
the compiler.
mutable keyword indicates that particular member of a structure
or class can be altered even if a particular structure variable,
class, or class member function is constant.
struct data
{
char name[80];
mutable double salary;
}
const data MyStruct = { "Satish Shetty", 1000 }; //initlized by
complier
strcpy ( MyStruct.name, "Shilpa Shetty"); // compiler error
MyStruct.salaray = 2000 ; // complier is happy allowed
What is reference ??
reference is a name that acts as an alias, or alternative
name, for a previously defined variable or an object. prepending
variable with "&" symbol makes it as reference. for example:
int a;
int &b = a;
What is passing by reference?
Method of passing arguments to a function which takes
parameter of type reference. for example:
void swap( int & x, int & y )
{
int temp = x;
x = y;
y = x;
}
int a=2, b=3;
swap( a, b );
Basically, inside the function there won't be any copy of the
arguments "x" and "y" instead they refer to original variables a
and b. so no extra memory needed to pass arguments and it is
more efficient.
When do use "const" reference arguments in function?
a) Using const protects you against programming errors that
inadvertently alter data.
b) Using const allows function to process both const and
non-const actual arguments, while a function without const in
the prototype can only accept non constant arguments.
c) Using a const reference allows the function to generate and
use a temporary variable appropriately.
When are temporary variables created by C++ compiler?
Provided that function parameter is a "const reference",
compiler generates temporary variable in following 2 ways.
a) The actual argument is the correct type, but it isn't Lvalue
double Cuberoot ( const double & num )
{
num = num * num * num;
return num;
}
double temp = 2.0;
double value = cuberoot ( 3.0 + temp ); // argument is a
expression and not a Lvalue;
b) The actual argument is of the wrong type, but of a type that
can be converted to the correct type
long temp = 3L;
double value = cuberoot ( temp); // long to double conversion
|
|
<<Previous Next>> |
|
Confined Topics
to C++ |
|
|
|
Related Topics to
C++ |
|
|
|
Other Sites for C++ |
|
Submit your link
|
|
Send more about C++ |
|
Send us your comments on C++,
if you want to share your knowledge on C++. We will
publish it on this site |
|