- Examples

In this lesson, we'll look at a couple of examples of type erasure.

Example 1: Type Erasure Using Object-Oriented Programming

Press + to interact
// typeErasureOO.cpp
#include <iostream>
#include <string>
#include <vector>
struct BaseClass{
virtual std::string getName() const = 0;
};
struct Bar: BaseClass{
std::string getName() const override {
return "Bar";
}
};
struct Foo: BaseClass{
std::string getName() const override{
return "Foo";
}
};
void printName(std::vector<BaseClass*> vec){
for (auto v: vec) std::cout << v->getName() << std::endl;
}
int main(){
std::cout << std::endl;
Foo foo;
Bar bar;
std::vector<BaseClass*> vec{&foo, &bar};
printName(vec);
std::cout << std::endl;
}

Explanation

The key point is that you can use instances of Foo or Bar instead of an instance for BaseClass. std::vector<BaseClass*> (line 35) has a pointer to BaseClass. Well, actually it ...

Access this course and 1400+ top-rated courses and projects.