Jan 31, 2011

Overloading operator()

Browsing through some of the open source code implementation in C++, came across the function void operator()()
Q. Why would one use operator() in the first place?
A. Simplicity of usage. Of course, less intuitive if you are seeing it's use for the very first time.

The program below implements a matrix and uses operator() as a replacement of subscript operator[] to retrieve and set values at the particular location.

#include <iostream>

//File: Matrix.h

class Matrix
{
public:
    Matrix(size_t rows, size_t cols);
    Matrix(const Matrix &m);
    virtual ~Matrix();

    Matrix& operator=(const Matrix &m);
    double& operator()(size_t row, size_t col);
    //double operator()(size_t row, size_t col) const;

    size_t getRows() const;
    size_t getCols() const;

private:
    Matrix();
    void copy(const Matrix &m);
    void init(double value);

    size_t _nrows, _ncols, _size;
    double *_data;
};

Excercise
Why is the method commented out in the above code?
//double operator()(size_t row, size_t col) const;

Read more ...

Jan 23, 2011

C Program - struct usage example

This is a follow up post on my last blog update Pointers in C - an eye opener. The program touches on the following -
1. Using struct as Employee record
2. Using pointer to Employee* as an employee list
3. Using void pointer and casting it to an appropriate type to avoid duplicate code
4. Allocating memory and freeing memory

struct Person
{
    char *name;
    size_t age;
};
typedef struct Person Employee;

struct Organization
{
    Employee **emplist;
};
typedef struct Organization Org;

A sample execution of the program should be as shown:


Read more ...

Jan 20, 2011

Pointers in C - an eye opener

My friend once asked me a problem in C involving struct and pointers. I was confident that the solution I had proposed would work untill I finally gave it a try.
Among the common mistakes i could not avoid were not allocating memory before trying to use the pointers and trying to dereference a pointer as p->q->*num :)

#include <stdio.h>

struct B
{
    char *str;
    int  *num;
};

struct A
{
    struct B *q;
};

int main()
{
    char *tstr = "Hello World";

    /**
     * 1. The program should copy the value tstr in str and print it
     * 2. The program should assign value 100 to num and print it 
     */
    struct A *p;
}

Read more ...