Friday 9 May 2014

Pointer To Member Operators

The pointer-to-member operators ->* and .* group left-to-right

Example of Pointer to Member Operators:



Example1: Pointer to member data
#include<cstdio>
class Test
{
public:
        int x;
        Test():x(5){}
        void display()
        {
                printf("x:%d\n",x);
        }
};
int main()
{
        Test obj;
        Test *objPtr=&obj;         //pointer to object "obj"
        int Test::*p = &Test::x;  //p is a pointer to member x of Test.
        obj.display();            // output:5
        obj.*p=7;                 //modify the content of x by using pointer p
        obj.display();            // output:7
        objPtr->*p=10;            //modify the content of x by using pointer p accessed by a pointer points to an object "obj".
        obj.display();            // output:10
}

Example2: Pointer to member function
#include<cstdio>
class Test
{
public:
        int x;
        Test():x(5){}
        void display()
        {
                printf("x:%d\n",x);
        }
};
int main()
{
        Test obj;
        Test *objPtr=&obj;                   //pointer to object "obj"
        void (Test::*ptr_display)();
        ptr_display = &Test::display;
        obj.display();                      //calling display function by object
        (obj.*ptr_display)();            //calling display function by pointer to member function
        (objPtr->*ptr_display)();           //calling display function by pointer to member function using object pointer
}

Friday 2 May 2014

Implicit Definition in CPP

In some circumstances, C ++ implementations implicitly define the default constructor (12.1), copy constructor (12.8), move constructor (12.8), copy assignment operator (12.8), move assignment operator (12.8), or destructor (12.4) member functions.
--- N3690_CPP-11_Draft, Page-No: 33


class C
{

};
By default contains the implicit defined functions:
class C
{
public:
    C(){ }  //default constructor
    C(const C&)  //copy constructor
    {
    }
    C& operator=(const C& x)     //copy assignment operator
    {
        return *this;
    }
    ~C(){ } //destructor
};
In case if any constructor is explicitly defined inside the class, compiler will override the default constructor. But other implicit constructor will still be there until it is not explicitly overridden by the programmer. Example:
class C
{
public:
    C(C& obj){ }
};
contains the implicit defined functions:
class C
{
public:
    /*C(){ }*/  //no default constructor
    C(C& obj){ }   //explicitly defined by programmer
    C(const C&)  //copy constructor
    {
    }
    C& operator=(const C& x)     //copy assignment operator
    {
        return *this;
    }
    ~C(){ } //destructor
};