John Matthews wrote:
> --- In [email protected], "Bill Cunningham" <bill...@...> wrote:
>> I would like to start writing code and calling functions in C 
>> code with a pointer to a function. This so I can learn
>> functions pointers.
> 
> Simple example:
> 
> #include <stdio.h>
> 
> static void inc(int *p) /* increment */
> {
>     (*p)++;
> }
> 
> static void dec(int *p) /* decrement */
> {
>     (*p)--;
> }
> 
> int main(void)
> {
>     void (*fnPtr)(int *p); /* function pointer */
>     int    i = 0;
> 
>     printf("i=%d\n", i);
>     fnPtr = inc;
>     fnPtr(&i);
>     printf("i=%d\n", i);
>     fnPtr = dec;
>     fnPtr(&i);
>     printf("i=%d\n", i);
> 
>     return 0;
> }

Now for a similar simple example in C++:

#include <stdio.h>

class Base
{
public:
   Base()  {}
   virtual ~Base()  {}

   virtual void Alter(int &) const  {}
};

class Inc : public Base
{
public:
   Inc()  {}
   virtual ~Inc()  {}

   virtual void Alter(int &Num) const  { Num++; }
};

class Dec : public Base
{
public:
   Dec()  {}
   virtual ~Dec()  {}

   virtual void Alter(int &Num) const  { Num--; }
};

void DoActionAndPrint(const Base &Action, int &Num)
{
   Action.Alter(Num);
   printf("Num = %d\n", Num);
}

int main(void)
{
   Base A;
   Inc B;
   Dec C;
   int Num = 0;

   DoActionAndPrint(A, Num);
   DoActionAndPrint(B, Num);
   DoActionAndPrint(C, Num);
}


Notice what is passed to DoActionAndPrint() is a const reference to the 
instance of the base class 'Base'.  When Alter() is called, it calls the 
most derived member function.  Behind the scenes there is a set of 
pointers to functions in what is called a 'vtable' so that calling the 
function in the base class actually ends up calling the derived class 
function (assuming correct use of the 'virtual' keyword across the chain 
built by the base-derived relationship).

http://en.wikipedia.org/wiki/Virtual_method_table

-- 
Thomas Hruska
CubicleSoft President
Ph: 517-803-4197

*NEW* MyTaskFocus 1.1
Get on task.  Stay on task.

http://www.CubicleSoft.com/MyTaskFocus/

Reply via email to