Note that there are some explanatory texts on larger screens.

plurals
  1. POAccessing Properties/Functions of Subclasses C++
    primarykey
    data
    text
    <p>I am having a design problem in my program because I need to occasionally access properties &amp; methods of subclasses that are all stored in a vector of base class pointers. My code looks something like this:</p> <pre><code>class B1; class B2; class Base { private: int id, a, b; public: virtual int getA() { return a; } virtual int getB() { return b; } virtual B1 *getB1() { return NULL; } //seems like a bad idea virtual B2 *getB2() { return NULL; } //to have these two functions Base(int newId) { id = newId; } }; class B1 : public Base { private: int x; public: int getX() { return x; } B1 *getB1() { return this; } }; class B2 : public Base { private: int y; public: int getY() { return y; } B2 *getB2() { return this; } }; class Thing { private: std::vector&lt;Base*&gt; bases; void addBase(Base *base) { bases.push_back(base); } void doB1Stuff(); void doB2Stuff(); void setAandB(int ID, int newA, int newB); //set a and b of one of the elements in bases vector based upon the id given }; </code></pre> <p>The problem is if I need to access x or y in Thing, like this below:</p> <pre><code>void Thing::doB1Stuff() { for(std::vector&lt;Base*&gt;::iterator it = bases.begin(); it != bases.end(); ++it) { if (it-&gt;getB1()) { //do stuff with b1 } } } </code></pre> <p>The code above should work, but if it seems a bad idea because one could easily forget to check if the pointer is null before using B1/B2 properties like this:</p> <pre><code>void Thing::doB2Stuff() { for(std::vector&lt;Base*&gt;::iterator it = bases.begin(); it != bases.end(); ++it) { std::cout &lt;&lt; it-&gt;getY(); //I believe this will crash the program if a NULL pointer is returned } } </code></pre> <p>My question thus is: what is a good way of accessing subclass properties? I was thinking of having two separate vectors for B1s and B2s in Thing, but that doesn't seem like a good idea either because I need to be able to set a and b easily. Any thoughts?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload