static array of base class pointers to point to derived classes dynamically ?
Hey guys,
here is the problem:
I have to keep an static array of pointers of type base class , and I should be able to assign each of these pointers to any of the derived class..
here is the code...
class Base
{
public:
static Base* basePtr[10];
}
class derived1 : public Base
{ }
class derived2 : public Base
{}
now in my main.cpp I want to be able to create objects of derived1 or derived2 and assign the basePtr to point to them....
how do I do that???
.....
...
derived1 d1
Base::basePtr[1] = &d1 // I tried this approach, the problem is...does this mean I have to have 10 different classes of d1 or d2 and then assign each of their references to the basePtr ??? Is there way to do this dynamically so that I do some thing like the following
Base::basePtr[1] = new derived1;
Pls help..
Re: static array of base class pointers to point to derived classes dynamically ?
Quote:
Originally posted by LudaLuda
now in my main.cpp I want to be able to create objects of derived1 or derived2 and assign the basePtr to point to them....
how do I do that???
Didn't you just do it in your example here?
Code:
derived1 d1;
Base::basePtr[1] = &d1;
//...
Base::basePtr[1] = new derived1;
Both are valid.
Quote:
I tried this approach, the problem is...does this mean I have to have 10 different classes of d1 or d2 and then assign each of their references to the basePtr ???
Now that is a different question. Also, there are no references in your example, only pointers. The problem you should be concerned about is whether the pointer will go out of scope, thereby making the Base array have invalid pointers stored.
By storing the address of a (potential) local variable (I don't know in what scope d1 is declared), that address is valid until d1 is destroyed when it leaves scope. Then your Base array will have a pointer to an invalid address. If you create an object dynamically, then it won't go out of scope until you explicitly delete it.
Regards,
Paul McKenzie