W0lf's Guide to Perl OOP for C/C++ Programmers

Wednesday, October 12, 2005

 

Classes and Objects

In C++, a class is merely an abstraction that serves as a specification, if you will, from which 'objects' get created at run-time. An object is an instance of a class -- It is the living organism that is made up from the DNA of its class.

So, for instance, in C++, if you had a class:

class CMyClass {
public:
int method1();
int method2();
};

declared in the file CMyClass.h, with the method implementations in file CMyClass.cpp, the Perl equivalent would be a file CMyClass.pm, containing:

#!/usr/bin/perl

package CMyClass;

sub method1 {
# Method Implementation
}

sub method2 {
# Method Implementation
}

Et Voila! You have a class.

Now I mentioned the two addressing operators "::", "->", and also the relationship between an object and its class.

We are all familiar with how objects come into being -- lets just recap:
- By 'static' allocation in the BSS as global variables or on the program stack as automatic variables.
- By dynamic memory allocation on the heap using new or 'placement' new.

Note that in C++, the actual allocation of the object is handled by the C++ run-time libraries. Of course, you can define your own allocation mechanism by overloading the 'new' and 'delete' operators. The 'constructor' for the object is then called after memory for the object has been allocated. In that sense, a C++ constructor is really only an 'initializer'.

Perl, however, does things a little differently.

In fact, Perl requires you to handle the allocation for the object yourself. This is usually done in the constructor method. So you could argue that Perl object constructors are constructors in the truest sense of the word.

Comments: Post a Comment



<< Home

Archives

October 2005  

This page is powered by Blogger. Isn't yours?