Changing data in a class member.

I've defined a class called cars and it has a member called potential.

Now all of the class definition is correct and I define it this way in main.

1
2
3
4
5
main() {

car*potential = new car {"ferrari")

}


Now I've tried delete potential and then create potential again, but I get errors.

Is there any way I can enter new data into that class and flush it of previous data. So that I can use that class member repeatedly?
Need more code, that's not quite enough material. By the way, shouldn't you be using member operator (.) rather than dereference (*)?
Not in this instance I'm afraid, but you'll see that in a minute.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class car
{
private:
string carModel;

public:
car (string carModel);
~car (){}

string returnModel()
{
return (carModel);
}
};

car::car (string carMod): carModel(carMod)
{}

int main()
{
car*potential = new car ("Ferrari");

potential->returnModel();
}

//I've found that the following doesn't quite do as expected. 

delete potential;

car*potential = new car ("Mercedes");
return 0;
}
Last edited on
OK, that needs some indenting.
I see now... you were making a dynamically allocated car, right?
So if you want to modify the class's data like that you could just create a member to modify the string member. Because the member is private you can't modify it directly but you could always form a member to get the job done.
Have you noticed that the delete code on line 28 is not in main?
as tummychow said, delete the } on line 24.

After you delete potential (28) your pointer is still there, (just doesn't point to an allocated memory location), so don't redeclare potential, just give it a new value. :
potential = new car ("Mercedes");

(also don't forget to delete potential again)
whoops, yeah, that was mainly just to show something I'd tried that didn't work.

Yeah that's pretty much what I meant, it's hard to write code in this text box and my copy function isn't working at the moment.

Perhaps something like

1
2
3
4
string clearData()
{
carModel = //clear it from here somehow? 
}


...that's complete bonkers. <.< I'm getting confused with the references to 'members'

That's a great idea R0mai. Didn't realise it left the pointer I thought it cleared everything.
Last edited on
Works perfect, thanks for your help.
Topic archived. No new replies allowed.