Search code examples
c++cgal

CGAL inheritance


How can I use an inherited class of a triangulation in the context of a triangulation in CGAL?

Basically I have the following code:

typedef CGAL::Exact_predicates_inexact_constructions_kernel K;

typedef CGAL::Triangulation_vertex_base_with_info_2<int,K> Vb;
typedef CGAL::Triangulation_face_base_with_info_2<int,K>   Fb;
typedef CGAL::Triangulation_data_structure_2<Vb,Fb>        Tds;
typedef CGAL::Delaunay_triangulation_2<K,Tds>              Delaunay;
typedef CGAL::Triangulation_2<K,Tds>                       Triangulation;

typedef Triangulation::Point Point;

...

Triangulation *t = new Delaunay;

...

// x and y are properly defined and instantiated
t->insert(Point(x,y));

Well, of course, Delaunay_triangulation_2 inherits from Triangulation_2

So, when I execute this code, the linking is done against the Triangulation_2 class, in other words, it does not executes a delaunay triangulation, instead it executes a normal triangulation (executing the parent class methods instead of the child methods).

I think this is because the insert method of Triangulation_2 is not declared as virtual so redefinitions won't work.

Do you know a way around this? Maybe using Constrained_triangulation_2 and Constrained_delaunay_triangulation_2? (those classes define some virtual methods, but i've read the source code and I don't think they can be used without adding the explicit constraints)

Any ideas?


Solution

  • I checked your program, you would need to reformat it a bit, so that it fits the generic programming model. Let me recall what your code does (the one available at github):

    1. reads the command line
    2. depending on the options, instantiates either a Triangulation or a Delaunay_triangulation on the heap
    3. uses this object for some processing, assuming that the methods are virtual (but they are not)

    A solution for your problem would be to put step 3 in a separate method, with the triangulation type as template parameter. Something like (I use your types and names):

    template < class Triangulation >
    void compute_mesh(int n_vertices, int max_x, int max_y)
    {
        Triangulation t;
        // DO WHATEVER YOU WANT WITH t
    }
    

    Then, in your main function, you would trigger the use of Delaunay or non-Delaunay triangulations in the following way:

    if (triang_type == 'D') 
        compute_mesh<Delaunay>(n_vertices, max_x, max_y);
    else 
        compute_mesh<Triangulation>(n_vertices, max_x, max_y);