Note that there are some explanatory texts on larger screens.

plurals
  1. POPolymorphism and array of pointers problem in C++
    primarykey
    data
    text
    <p>I'm working on a project and it's in a stage that I don't know what's wrong. Here's the simplified version:</p> <p>The code:</p> <pre><code> class Base { // This base class is pure abstract public: virtual ~Base(); // Necessary to trigger destructors in inherited classes virtual baseFunc() = 0; }; class DerivedA : public Base{ public: DerivedA(SomeClassUseBase * tmp){ tmp -&gt; register(this); } ~DerivedA(); void baseFunc(){ // do something here that's only for DerivedA } }; class DerivedB : public Base{ public: DerivedB(SomeClassUseBase * tmp) { tmp -&gt; register(this); } ~DeriveB(); void baseFunc(){ // do something here that's only for DerivedB } }; class SomeClassUseBase { private: Base ** basePrt; unsigned int index; public: someClassUseBase(int num) { basePrt = new Base*[num]; //create an array of pointers to the objects index = 0; } void register( Base * base ){ //i tried *(basePrt[index]) = *base, but got the same problem basePrt[index] = base; index = index + 1; } void checkList() { for (int i = 0; i &lt; index ;i++){ next = basePrt[i]; next -&gt; baseFunc(); //fails here } } }; int main() { SomeClassUseBase tmp = new SomeClassUseBase(5); Base *b[5]; for ( i = 0; i &lt; 5; i += 1 ) { if ( i % 2 == 0 ) { b[i] = new DerivedA(&amp;tmp); } else { b[i] = new DerivedB(&amp;tmp); // the object pointed by tmp::basePrt[0] is lost after this line } // if } // for tmp.checkList(); //crashes here since tmp.bastPrt[0] points to null } </code></pre> <p>The problem is that when in main, i reach the line when the first DerivedB is created, the already created DerivedA pointer by tmp.basePrt[0] is lost some how. I don't know why but i suspect that this has sth to do with polymorphism? Please help!! thanks!!</p> <p>Edit:</p> <p>Didn't quite get the code correct the first time, sorry... </p>
    singulars
    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.
 

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