I would like to use the same variable but I want to reinstantiate it. How do I do it in c++?
Here is a simple example. I try to reinstantiate t1 but it doesn’t compile. (Notice t1 is stored in the stack. I’m not asking how to do dynamic memory allocation)
class Table
{
private int feet;
public Table(int x)
{
feet=x;
}
}
Table t1(3);
t1(4);
The answer is a wonderful language feature called assignment.
In short, you can change the value of a variable – even a variable of a type you have defined yourself – by using the
=symbol.As a matter of fact your code is already using assignment, namely in the constructor.
In the example below I’ve replaced that original code’s assignment with an initializer, because initializers are generally preferable (choose them when there is no good reason to use assignment for initializating members).
The assignment that updates the value of
t1, effectively “reusing”t1, can go like this:Note 1: it’s possible to define a type so that assignment is prohibited.
Note 2: since you have defined a conversion constructor, one that accepts a single argument, and since that constructor is not
explicit, the assignment above can be expressed more simply (but perhaps less clearly) as …… which results in exactly the same.
Note 3: your code as presented would not have compiled, it was just “like” C++, it was not C++. I’ve fixed the errors (I think, but I didn’t bother to run it through a compiler). But in general it’s not always possible to know or even guess whether errors in the presented code have something to do with the question, so please copy and paste real code.
Cheers & hth.,