Hi

I have a question regarding runtime polymorphism.

I have for example

derived A;
base *B;

and I do this

B=&A;

if A goes out of scope does this mean the pointer B is a bad pointer meaning it does not point to anywhere? If so, does this mean I still need to have somewhere in my program an instance of class derived?

thanks

Recommended Answers

All 4 Replies

if A goes out of scope does this mean the pointer B is a bad pointer meaning it does not point to anywhere?

Yes, A goes out of scope and its destructor is called. You should really
have B in the same scope as A. That means B shouldn't be global.

If so, does this mean I still need to have somewhere in my program an instance of class derived?

care to elaborate?

>if A goes out of scope does this mean the pointer B is a
>bad pointer meaning it does not point to anywhere?

Yes, B is a bad pointer. It still points to somewhere, but the address it points to is a destroyed object, or (even worse) a new object that B is an unexpected alias of. This is called a dangling pointer.

>If so, does this mean I still need to have somewhere
>in my program an instance of class derived?

Pretty much. The lifetime of the object must match or exceed the lifetime of the pointer. Usually this is done with dynamic allocation so that one doesn't need to manage two unique entities (the object and the pointer to it).

Pretty much. The lifetime of the object must match or exceed the lifetime of the pointer. Usually this is done with dynamic allocation so that one doesn't need to manage two unique entities (the object and the pointer to it).

How can I use dynamic allocation?

>How can I use dynamic allocation? new (or new[] ) and delete (or delete[] ) are the most common way. I suggest you refer to your C++ book for how to use them. We're typically hostile toward people who don't do basic research before asking a question.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.