Wednesday, November 19, 2008

Classes and Objects


Imagine that you have created a simple class in C++ called xxx. It has several member functions, named MethodA, MethodB, and MethodC.

Each member function accepts parameters and returns a result. The class declaration is shown here:


class xxx {

public:

int MethodA(int a);

int MethodB(float b);

float MethodC(float c);

};


The class declaration itself describes the class. When you need to use the class, you must create an instance of the object. Instantiations are the actual objects; classes are just the definitions. Each object is created either as a variable (local or global) or it is created dynamically using the new statement. The new statement dynamically creates the variable on the heap and returns a pointer to it. When you call member

functions, you do so by dereferencing the pointer. For example:


xxx *px; // pointer to xxx class

px = new xxx; // create object on heap

px->MethodA(1); // call method

delete px; // free object


It is important for you to understand and recognize that COM follows this same objected oriented model. COM has classes, member functions and instantiations just like C++ objects do. Although you never call new on a COM object, you must still create it in memory. You access COM objects with pointers, and you must de-allocate them when you are finished.


When we write COM code, we won't be using new and delete. Although we're going to use C++ as our language, we'll have a whole new syntax. COM is implemented by calls to the COM API, which provides functions that create and destroy COM objects. Here's an example COMprogram written in pseudo-COM code.


ixx *pi // pointer to xxx COM interface

CoCreateInstance(,,,,&pi) // create interface

pi->MethodA(); // call method

pi->Release(); // free interface


In this example, we'll call class ixx an "interface". The variable pi is a pointer to the interface. The method CoCreateInstance creates instance of type ixx. This interface pointer is used to make method calls. Release deletes the interface. I've purposely omitted the parameters to CoCreateInstance. I did this so as not to obscure the basic simplicity of the program. CoCreateInstance takes a number of arguments, all of which need some more detailed coverage. For now, let's take a step back and look at the bigger issues with COM.


0 comments: