Reputation: 337
I have a very basic question about a class object. After the class has been created, we need to create a class object. At this point, I'm a bit confused to make either *object
or object
. Example:
CClass object
CClass *object
What is the difference both of them? And to access class function i need to use dot '.'
and arrow '->'
. I know dot and arrow used to access class function, but what is the significant meaning for both dot and arrow?
Upvotes: 2
Views: 147
Reputation: 6171
When used in a function, your first method creates an object on the stack, and methods are called using the .
notation.
CClass obj;
obj.method();
Important: The object will be destroyed regardless of how the processing leaves the enclosing function.
When used in a function, your second method creates an object on the heap. and because you are dealing with a pointer, methods must be called using ->
notation
CClass *obj = new CClass(); // obj is a pointer to a new object on the heap
obj->method();
Important: This object will not be destroyed when you leave the function, meaning you have to manage its lifetime elsewhere. If you need to destroy the object you can use:
delete obj;
Upvotes: 7
Reputation: 5341
The version with the star in front is declaring a pointer to an object - you need to allocate space for this with the "new" keyword and make sure the memory gets freed using "delete" when the object is finished with.
The other (non-starred) declaration declares the object as a local variable, which gets space automatically allocated on the stack and which gets cleaned up automatically when it goes out of scope.
It's an important difference to understand, you might want to work through a good C++ tutorial to get a good explanation of how the language works. There's one at http://www.cplusplus.com/doc/tutorial/.
Upvotes: 2
Reputation: 92854
CClass object
defines an object named object
of type CClass
.
CClass *ptr_object
defines a pointer ptr_object
to an object of type CClass
I know dot and arrow used to access class function, but what is the significant meaning for both dot and arrow?
ptr_object->func()
is semantically equivalent to (*ptr_object).func()
Upvotes: 3
Reputation: 10381
The second line is an example of a pointer to an object. The arrow -> is shorthand for dereferencing the pointer and accessing a member.
CClass * object;
//CClass has a public method Go and a public member variable Mine
object->Go(); //shorthand for (*CClass).Go()
Upvotes: 1