This example illustrates the most primitive form of C++ class wrapping performed by SWIG. In this case, C++ classes are simply transformed into a collection of C-style functions that provide access to class members.
/* File : example.h */
class Shape {
public:
  Shape() {
    nshapes++;
  }
  virtual ~Shape() {
    nshapes--;
  }
  double  x, y;
  void    move(double dx, double dy);
  virtual double area() = 0;
  virtual double perimeter() = 0;
  static  int nshapes;
};
class Circle : public Shape {
private:
  double radius;
public:
  Circle(double r) : radius(r) { }
  virtual double area();
  virtual double perimeter();
};
class Square : public Shape {
private:
  double width;
public:
  Square(double w) : width(w) { }
  virtual double area();
  virtual double perimeter();
};
/* File : example.i */
%module example
%{
#include "example.h"
%}
/* Let's just grab the original header file here */
%include "example.h"
Note: when creating a C++ extension, you must run SWIG with the -c++ option like this:
% swig -c++ -tcl example.i
set c [new_Circle 10.0]
Note: when accessing member data, the name of the base class must be used such as Shape_x_getShape_x_set $c 15 ;# Set member data set x [Shape_x_get $c] ;# Get member data
puts "The area is [Shape_area $c]"
Shape_area $c # Works (c is a Shape) Circle_area $c # Works (c is a Circle) Square_area $c # Fails (c is definitely not a Square)
delete_Shape $c # Deletes a shape
set n $Shape_nshapes # Get a static data member set Shapes_nshapes 13 # Set a static data member
Circle c 10 # c becomes a name for the Circle object
c configure -x 15 ;# Set member data set x [c cget -x] ;# Get member data
puts "The area is [c area]"
rename c "" # c goes away
set n $Shape_nshapes # Get a static data member set Shapes_nshapes 13 # Set a static data member