Quick pointer question

Hello pro's,
I'm studying pointers and i'm having trouble using a get and set function of an object that is a pointer of a class (think I worded that right), if anyone could tell me what i'm doing wrong it would be a huge help :)
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
33
34
35
36
 #include <iostream>
#include <string>

using namespace std;
class thing
{
public :
	string *x;
public:
	thing()
	{
		x = new string;

	}
	string getx()
	{
		return *x;
	}
	void setx(string x)
	{
		*this->x  =x;
	}
	~thing()
	{
		delete[] x;
	}
};

int main()
{
	thing *object;
	object = new thing;

	object.setx("hey");   // i tried using *object as well
	cout << object.getx();
}
1
2
3
4
5
6
7
8
9
10
11
void setx(string x)
{
	*(this->x) = x;
}

...

int main()
{
      (*object).setx("hey");    // or object->setx("hey")
      cout << (*object).getx();   // or object->getx() 


Last edited on
Thank alot! I forgot all about the -> pointer lol
Something else to note: The object std::string is itself not an array, it has it's own destructor. If you tried to delete 'object' right now, with the way your destructor is written, you would get a run-time error.
Topic archived. No new replies allowed.