Thursday 1 December 2011

C++ Programing Questions And Answers-3


Q. What is reference ?
Ans. 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; 
Q. What is passing by reference?
Ans. 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 = temp;
}
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. 
Q. When do use "const" reference arguments in function?
Ans.
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.
Q. When are temporary variables created by C++ compiler?
Ans. 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 Cube(const double & num)
{
num = num * num * num;
return num;
}
double temp = 2.0;
double value = cube(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
Q. What is virtual function?
Ans. When derived class overrides the base class method by redefining the same function, then if client wants to access redefined the method from derived class through a pointer from base class object, then you must define this function in base class as virtual function.
class parent
{
void Show()
{
cout << "i'm parent" << endl;
}
};
class child: public parent
{
void Show()
{
cout << "i'm child" << endl;
}
};
parent * parent_object_ptr = new child;
parent_object_ptr->show() // calls parent->show() i
now we goto virtual world...
class parent
{
virtual void Show()
{
cout << "i'm parent" << endl;
}
};
class child: public parent
{
void Show()
{
cout << "i'm child" << endl;
}
};
parent * parent_object_ptr = new child;
parent_object_ptr->show() // calls child->show()

No comments:

Post a Comment