MY mENU


Monday, 15 October 2012

What is virtual function?

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() 

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 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

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 = 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.