SOLVED!!! Why do I have to do it like that - why can't I do it like this???

Started by
7 comments, last by darenking 18 years, 7 months ago
I'm creating an object then deleting it after accessing one of its methods. I'm doing it like this:

		Creator* creator = new Creator();
		if ( creator->File() )
		{
			delete creator;
		}


It looks daft to me, as it looks like I'm creating a pointer to an object then dereferencing it. Why can't I just create an object instead of a pointer to an object, I thought. So I tried it like this:

		Creator creator = new Creator();
		if ( creator.File() )
		{
			delete creator;
		}


...but I get an error, "converstion from 'Creator*' to non-scaler type 'Creator' requested". What can it all mean? Was just hoping to simplify things a little. [Edited by - darenking on August 30, 2005 8:18:35 AM]
Advertisement
-> is the C++ (and C) shortcut for specifying members of classes that are pointed to. It is a shortcut, because the command that more accurately reflects what is going on is
(*creator).File()
but it makes code more readable. C/C++ does not allow you to use the . operator as a member-of-class-pointed-to reference because a pointer IS a variable.

Hope that helps,
Twilight Dragon
{[JohnE, Chief Architect and Senior Programmer, Twilight Dragon Media{[+++{GCC/MinGW}+++{Code::Blocks IDE}+++{wxWidgets Cross-Platform Native UI Framework}+++
With the 'new' keyword you explicitly request a pointer.

You can do it like this:
Creator creator;
creator.File();

Once creator is out of scope it is automatically deleted.
new and delete are used only to allocate memory dynamically, therefore only for pointers. To create a simple instance of the class:
Creator creator();

Then you can use it and it is destroyed automatically when it goes out of scope.
The new operator allocates memory and returns a pointer to the type you called the constructor for:
Creator* pCreator = new Creator();pCreator->DoStuff();


You could do it the way you like only it does not involve a call to new. The object will be created:
Creator creator;creator.DoStuff();


Greetz,

Illco
With the 'new' keyword you explicitly request a pointer.

You can do it like this:
Creator creator;
creator.File();

Once creator is out of scope it is automatically deleted.
new and delete only work with pointers. If you use the second version, you need not use new and delete at all because the compiler will allocate and deallocate stack memory for the variable for you.
Well I suppose that is cleared up by now...
Yes, that is well and truly cleared up. It's just the same as declaring anything else, such as a string or an int. I'm such a dullard.

Off to snog a mallard.

This topic is closed to new replies.

Advertisement