jeudi 8 avril 2021

Have a C++ variable able to be either Class Foo or Class Bar

I am interested to write a printer to output two different formats. Let's call them txt and csv.

Can something like below be implemented in C++?

class Printer {
public:
  virtual void header() = 0;
};

class CSV : Printer {
public:
 void header() { printf("csv\n"); }
};

class TXT : Printer {
public:
 void header() { printf("txt\n"); }
};

int decider(int type) {
  auto prt;
  if (type == 1) {
     prt = new CSV;
  } else {
     prt = new TXT;
  }
  prt.header();
}

If not, what's an alternative to doing something similar?

Aucun commentaire:

Enregistrer un commentaire