'new' Operator for structs/classes

I'm somewhat new to using the 'new' operator, and I need to use it for a struct/class, but I'm not entirely sure how. This is my code, which doesn't work:

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
#include <iostream>

using namespace std;

class myclass 
{
public:
	int type;
	void printexample()
	{
		cout << "example" << endl;
	}
};

int main()
{
	int * pl = new int;
	myclass * p2 = new myclass;
	myclass p2;

	p2.type = 14;
	p2.printexample();

	* pl = 24;
	cout << * pl << endl;

	system("PAUSE");
	return 0;
}


Which retruns the error:
1
2
3
4
5
6
7
1>c:\users
1>c:\users\-----\documents\visual studio 2010\projects\cursestest\cursestest\cursestestmain.cpp(21): error C2228: left of '.type' must have class/struct/union
1>          type is 'myclass *'
1>          did you intend to use '->' instead?
1>c:\users\-----\documents\visual studio 2010\projects\cursestest\cursestest\cursestestmain.cpp(22): error C2228: left of '.printexample' must have class/struct/union
1>          type is 'myclass *'
1>          did you intend to use '->' instead?
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========


I'm pretty inexperienced with this sort of coding, so I have absolutely no idea as to what to do. Any help would be appreciated.
Last edited on
you declared a myclass class with the same name of a myclass pointer.
What the error says is to use '->' instead of '.' for class pointers.
If you keep 'myclass p2' keep the '.'
If you keep 'myclass * p2...' use '->'
Last edited on
closed account (zb0S216C)
I see a memory leak at 2 sites: Lines 17 & 18. Every call to new should have a corresponding call to delete[1]. C++ doesn't have a garbage collection system, like Java, or C# (except for C++/CLI -- Microsoft's idea of garbage collection for C++ (and a terrible one at that)). You allocate memory, you deallocate it. Also, you don't seem to have grasped the concept of pointers. That being said, you shouldn't do DMA if you don't fully understand pointers.

References:
[1] http://www.cplusplus.com/reference/std/new/


Wazzak
Last edited on
Topic archived. No new replies allowed.