views:

59

answers:

3

I can't seem to get my code to create either a child class or parent class, depending on input. Here's the code:

BST<countint> t;
if (rst)
  RST<countint> t;
t.print_type()    // always prints "BST"

RST is a child class of BST.

print_type() is just a test method I wrote. RST only really inherits one method, repair(), which is virtual void in both RST and BST. repair() is called by one other method, insert(), which is virtual bool in BST (parent) and not changed in RST.

A: 

How is print_type() implemented?

Take a look at your use of virtual.

(is print_type something you wrote or a compiler specific debug call?)

Martin Beckett
+1  A: 

You have two distinct variable declarations. The second one goes out of scope immediately, leaving the original declaration as the only one still in effect. You're calling print_type on the first variable, not the second.

You cannot change the type of a variable. A variable's type is constant. The first t variable has type BST<countint>, and the second t variable has type RST<countint>. The second variable temporarily hides or shadows the first variable, but that effect goes away after the conditional statement ends (which is on the very next line). Some compilers would have warned you that the second t wasn't used. (If your compiler warned you, then you should have mentioned that in the question; never ignore a compiler warning.)

If you want t to refer to values of different types, then you should use pointers. Declare t as a BST<countint>*, and then determine how to assign it a value. For example:

BST<countint>* t;
if (rst)
  t = new RST<countint>;
else
  t = new BST<countint>;
Rob Kennedy
Thank you very much! Sorry for the bad code, I'll remember to compile first next time.
jawonlee
A: 
BST<countint> t;
if (rst)
    RST<countint> t;
t.print_type()    // always prints "BST"

The t inside the if-block is destructed once the if-block ends. Once it has ended, t object declared with BST<countint> t.

I'm a C++ noob, but I think you need to use a pointer type here:

BST<countint> *t;

if (rst)
{
    // this "t" refers to the one declared above, not a distinct one
    // declared within [and bound by the scope of] this if-block
    t = new RST<countint>;
}
else
{
    // likewise
    t = new BST<countint>;
}

t->print_type();

delete t;
dreamlax