Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variant vs Inheritance [closed]

Let's suppose I'm writing a compiler for some programming language. It is common to use abstract syntax tree (AST) as an internal representation. I can see two possible ways to design it:

  1. using boost::variant
  2. using inheritance

As hierarchy of nodes is fixed - boost::variant will suffice.

My question is what are the advantages and disadvantages of each approach from points of maintability and runtime efficiency?

like image 489
justanothercoder Avatar asked Jul 04 '15 19:07

justanothercoder


1 Answers

Using boost::variants will work, but will require you to use visitor pattern extensively to exploit the content of a variant object. If later you extend the number of types used in your variant, you'll have to maintain all the visitors that you've implemented.

With inheritance, you have the advantage of being able to use polymorphism. Later extension will be straightforward : simply derive one of the existing base and override the polymorphic functions, without touching the rest of the code.

like image 128
Christophe Avatar answered Oct 23 '22 19:10

Christophe