Category : polymorphism

While writing my first big project in C++, I encountered a problem which I wasn´t able to solve using google and documentation alone. I cannot figure out, why this dynamic_cast fails, even though r is pointing to a MeshRenderer Object. for (RenderEventConsumer* r : d->getConsumers()) { glUseProgram(mPickingShader->apiID); MeshRenderer* m = dynamic_cast<MeshRenderer*>(r); //returns nullptr if (m) ..

Read more

I am trying to set up a kinda double polymorphic map in C++. I have something like this: class Base{ }; class Derived : Base{ }; template <typename T> class ClassTemplate{ std::vector<T> vec; }; class TemplatedBase : ClassTemplate<Base>{ }; class TemplatedDerived : ClassTemplate<Derived>{ }; I want to create a function that takes in a std::map<std::string, ..

Read more

I have a BaseMessage class from which I derive several different DerivedMessage subclasses and want to send them like this: class BaseMessage { public: virtual std::vector<uint8_t> data() const noexcept = 0; virtual ~BaseMessage() = default; […] } class DerivedMessage : public BaseMessage { public: […] std::vector<uint8_t> data() const noexcept override { return m_data; } private: ..

Read more

I am trying to create a Dataset class for a machine learning library. The objective is for the class to hold a vector of a generic type for the data/features, and another for the labels. There is also the possibility of having an unlabelled dataset, in which case, the second vector is unnecessary. Below is ..

Read more

class Fruit { public: virtual int anyMethod() { return 0; } }; class Comparable { public: virtual int compareTo(Comparable *other) = 0; }; class Apple : public Fruit, public Comparable { int m_state; public: Apple(int state) { this->m_state = state; } int compareTo(Comparable *other) { return this->m_state – ((Apple *)other)->m_state; } int anyMethod() { return ..

Read more

Suppose I have textbook example of CRTP (curiously recurring template pattern) and want to create a container of Base* without specifying the Derived information to traverse and call interfaces kind of polymorphically. template<typename T> class Base { public: void f() { static_cast<T*>(this)->f(); } }; class Derived1 : public Base<Derived1> { public: void f() { std::cout ..

Read more

Given the following structure of a Parent class and 2 childs. class Data{ protected: int data; }; class TreeData: public Data{ // something }; class PlantData: public Data{ // something }; Then, somewhere else I have another class structure to recover the data: class RecoverData{ protected: string ip; int commTimeout; public: virtual Data getData(); }; ..

Read more