Wednesday, 24 March 2010

C++ Trivia

Q. What is the single colon operator doing in the constructor definition?

class Temp {
const int member;
public:
Temp(int m);
};
Temp::Temp(int m)
:member(m) { }

A. A colon here is used to initialize a member constant.


Q. What is the difference between the following two codes?
a)
template< class T, class U, class V>
T doSomething(T t, U u, V v)
{
return t + u + v;
}
b)
template< typename T, typename U, typename V>
T doSomething(T t, U u, V v)
{
return t + u + v;
}

A. Technically there isn't. It is better practice to use the class keyword in templates when there is a class expected, and typename for anything else.


Q. What is an accessor function?
A. An accessor function is one which does not modify any members of a class. The const keyword is used to denote an accessor function. For example,

bool student::checkAge() const;

This does not provide any extra functionality, but it is a good practice to use the const keyword wherever possible, as it can help eliminate any possible bugs.

0 comments: