Monday, September 29, 2008

comparing class syntax in C++, Java, PHP, Perl and Python

As I recently started learning Python one of the things I noticed which I didn't like is the class syntax. So I wrote some minimal hello world programs in the languages I recently used to show the difference:


#include <iostream>

class Hello {

private: char *value;

public: Hello(char *newvalue) {
value = newvalue;

public: void hello() {
std::cout << this->value;

int main() {
Hello hello("hello\n");
I like the C++ syntax, it is the language which introduced me to OOP and it it clearly states what bits are what without too wordy syntax.


class Hello {
private String value;

public Hello (String newvalue) {
this.value = newvalue;

public void hello(){

class main {
public static void main(String args[]){
Hello hello = new Hello ("hello");
hello.hello ();
Also very nice, a bit clearer than C++.

PHP: hello.php


class Hello {
private $value;

function __construct($newvalue) {
$this->value = $newvalue;

function hello() {
echo $this->value;

$hello = new Hello("hello\n");
From the dynamic languages this one is the clearest. Except of the __construct() constructor, where I prefer the ClassName() syntax (which still works in PHP5)


package Hello;

sub new {
my ($class,$newvalue) = @_;
bless { newvalue => $newvalue }, $class;

sub hello {
my $this = shift;
print $this->{newvalue};

package main;

$main::hello = new Hello("hello\n");
I always hated objects (and functions) in Perl, there is no parameter syntax for functions or methods. Most of it is not enforced and you can use functions in objects in thousands different ways.


class Hello:
_value = ""

def __init__(self,newvalue):
self._value = newvalue

def hello(self):
print self._value;

hello = Hello("hello")
A lot clearer than Perl, but also a lot of convention instead of forced syntax. I got used to the indention by now. But I hate that I have to specify "self" as the first parameters, the __init__ syntax and the underscore prefixing of private or protected variables. At least it has proper function parameters.

No comments:

Post a Comment