Skip to content

Instantly share code, notes, and snippets.

@j-c-cook
Created May 18, 2023 13:11
Show Gist options
  • Save j-c-cook/564461e3ab8f1b9b0b7ed901aa0d5074 to your computer and use it in GitHub Desktop.
Save j-c-cook/564461e3ab8f1b9b0b7ed901aa0d5074 to your computer and use it in GitHub Desktop.
Vector of pointers to derived classes constructor
cmake_minimum_required(VERSION 3.25)
project(vectorOfPointers)
set(CMAKE_CXX_STANDARD 17)
add_executable(vectorOfPointers main.cpp)
#include <iostream>
#include <vector>
class Base {
public:
Base() = default;
virtual ~Base() = default;
virtual const char * object_name() = 0;
};
class A : public Base {
public:
A() : Base() {std::cout << "Construct A" << std::endl;}
~A() override = default;
const char * object_name() override {
return "A";
}
};
class B : public Base {
public:
B() : Base() {std::cout << "Construct B" << std::endl;}
~B() override = default;
const char * object_name() override {
return "B";
}
};
// https://stackoverflow.com/a/44192185
template<class T> Base* create()
{
return new T;
}
int main() {
// SINGLE
Base* (*createMyClass)(void) = create<A>;
Base* myClass = createMyClass();
// VECTOR OF FUNCTION POINTERS
std::vector<Base * (*)()> functions;
functions.push_back(create<A>);
functions.push_back(create<B>);
for (auto c : functions) {
Base * obj = c();
std::cout << "Object name: " << obj->object_name() << std::endl;
delete obj;
}
// ARRAY OF FUNCTION POINTERS
Base * (*createPage[2]) ();
createPage[0] = create<A>;
createPage[1] = create<B>;
for (int i=0; i<2; i++) {
Base * obj = createPage[i]();
std::cout << "i: " << i << " Object name: " << obj->object_name() << std::endl;
delete obj;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment