Tuesday, August 28, 2007

C++ keywords

mutable keyword:
----------------

The mutable keyword can only be applied to non-static and non-const data members of a class. If a data member is declared mutable, then it is legal to assign a value to this data member from a const member function.

class CMyClass
{
int a;
mutable int b;
public:

CMyClass(int x)
:a(x),b(x)
{}


int getValueA() const
{
a++; //Error! we cant modify a variable in
//const member function.
return a;
}

int getValueB() const
{
b++; //This is valid since the variable is declared as
//mutable
return b;
}

};

C++ keywords

explicit keyword:
-----------------

In C++ it is possible to declare constructors for a class, taking a single parameter, and use those constructors for doing type conversion.

class CMyClass
{
int a;
public:
CMyClass(int x) :a(x) {}
};

void fun(const CMyClass& a){ cout<<"Implicit Conversion";}

int main(int argc, char* argv[])
{
fun(10); //Implicit Conversion of integer to type CMyClass
return 0;
}

A declaration like:
CMyClass obj = 37;
says to call the CMyClass(int) constructor to create an CMyClass object from the integer value. Such a constructor is called a "converting constructor".

However, this type of implicit conversion can be confusing, and there is a way of disabling it, using a new keyword "explicit" in the constructor declaration:

class CMyClass
{ int a;
public:
explicit CMyClass(int x) :a(x) {}
};

void fun(const CMyClass& a){ cout<<"Implicit Conversion";}

int main(int argc, char* argv[])
{
fun(10); //Error! cannot convert from 'const int' to 'const class CMyClass
fun( CMyClass(10) ); // This works fine.
return 0;
}

Saturday, August 25, 2007

Friend Function

The private member data of a class can be accessed only by the class member functions. Well there is one exception in C++ language. A friend function will be friendly with a class even though it is not a member of that class. A friend function is allowed to access the private members of that class.

Basically, its violating the encapsulation. But it improves the code.

Thinking in such a way that a bigger problem is broken into halves.


How the friend function is called???

The friend function is called like f(x), while a member function is called x.f().





Example:


#include
using namespace std;

class Car
{
private:
int speed;
char color[20];

public:
Car()
{
speed=20;
strcpy(color,"red");
}
friend void display(Car& c);
};
void display(Car& c)
{
cout<< c.speed;
cout<< c.color;
}


void main()
{
Car c;
display(c);
}