FANDOM


Method prototypes are like Virtual functions in that they are declared in a class or interface, and are overridden by other code. A prototype is missing the method body, and has a semicolon after it to end the line.

void prototypeExample(int iArg, LPSTR iStr); is an example of a prototype.

To make a prototype functional, you must declare the override with a method body.

void prototypeExample(int iArg, LPSTR iStr)
{
   iArg++;
   printf(iStr);
}

Prototypes are normally used to make a method aware of another method before its declaration. For example, in windows programming, the WndProc method is normally declared after the WinMain method. The problem with this is that the WinMain method needs access to WndProc, but the access cannot be granted because WinMain comes earlier in the code than WndProc does. To solve this problem, use a prototype.

int function1()
{
   int i;
   function2(i);
   return i;
}
void function2(int q)
{
   q++;
}

The above code will generate an error, because function1 tries to call function2, but the program is not yet aware of its existance.

void function2(int);
int function1()
{
   int i;
   function2(i);
   return i;
}
void function2(int q)
{
   q++;
}

This code will work. Notice that the prototype doesn't name the variable q. Arguments declared in prototypes do not necessarily need the same names as the arguments in the override. In fact, they don't need names at all, as long as they have the same variable types (int, float, etc).

Prototypes are a very fundamental code concept, and are used extensively in classes. Here is an example of a prototype applied in this manner.

contents of PrototypeSample.h:

class ProtoSamp
{
 public:
    void methodA(); /this method will print the word "Hello Prototype!" using printf.
    void methodB(CHAR*, int); ///this method will print the string given a certain number of times.
    int methodC(int, int, bool); ///this method will add the two ints together, and if the bool is true, will invert the sign of the result.
    bool methodD(bool); ///this method will simply invert the value of the bool passed to it.
};


contents of PrototypeSample.cpp:

#include <stdio.h>
#include "PrototypeSample.h"
void ProtoSamp::MethodA()
{
   printf("Hello Prototype!");
} 
void ProtoSamp::MethodB(CHAR* toprint, int Ntimes)
{
   for (int i=0; i<Ntimes; i++)
   {
      printf(toprint);
   }
}
int ProtoSamp::MethodC(int opA, int opB, bool invert)
{
   int out;
   out = opA + opB;
   if (invert) out = -out;
   return out;
}
bool ProtoSamp::methodD(bool bIn)
{
   return NOT(bIn);
}

See how the function prototypes are first declared in the H file, then overridden in the cpp file?

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.