Dissecting Code

Sunday, July 18, 2010

Virtual Functions

Consider the following:


#include <iostream>

using namespace std;

class A
{
public:
virtual void func1( int a ){ cout<<"A::func1"; }
virtual void func2( int i=20 ){ cout<<i; }
};

class B: public A
{
public:
void func1( float a ){ cout<<"B::func1"; }
void func2( int i=40 ){ cout<<i; }
};

int main(int argc, char* argv[])
{
A* pb=new B;
pb->func1(1);
pb->func2();
return 0;
}



Can you guess the output for the same?



pb->func1(1) => A::func1!! This is so, because, B::func1 hides( as a result of overloading) A::func1, rather then override it. And in C++, overload resolution is done on the static type, as it is done at compile time.


pb->func2() => 20!! This is so because, although B::func2 is called, the compiler picks up the default value from the base class. So, default values should be the same down the class hierarchy.


As an aside, the C++ standard states that built in conversions have more priority then user defined conversions.


Source: http://www.gotw.ca/gotw/005.htm

Labels: ,

Monday, July 12, 2010

Of constants and R and L values

 

RValue: A value that can appear on the right of an expression only
LValue: A value that can appear on the left of an expression. An LValue is converted to an RValue implicitly. The vice-versa does not hold.

An important point: only LValues can be bound to references to non-constants. A temporary object is a RValue.

Consider the following:

#include <iostream>

using namespace std;

class A
{
public:
~A(){ cout<<"A"; }
};

class B: public A
{
public:
~B(){ cout<<"B"; }
};

B factory()
{
B temp;
return temp;
}


int main()
{
const A& obj = factory();
return 0;
}



This is valid in standard C++, as the const used along with the reference forces the life of the temporary object to the end of the scope of the block rather than the scope of the expression (which is generally the case for temporaries). The const in necessary for performing the above magic. Note here, we have no need for a virtual destructor too!!



Source: http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/

Labels: ,