~Image??

1
2
3
Image(){ };
~Image(){ };
Image(string, bool, float);


Hi, can I know what's above line means? And what is ti for? Thanks :)
Line one is a default constructor, line 2 is the destructor, and line 3 is another constructor
Thanks :)
Is that destuctor same like cvDestroyWindow()?
Last edited on
Not quite. Destructors are called automatically whenever the object dies. They are preceded by the tilde, ~
http://www.cplusplus.com/doc/tutorial/classes/

Image () is the default constructor that sets all of the elements inside a class to a default value usually 0.

Image(string, bool, float); is the argument constructor that sets the elements inside a class to the specified values.

~Image(){ }; is the destructor that frees any elements that are on the heap. For example a pointer int* p = new int needs to be freed by the end program so the destructor frees them for you.

I hope that makes sense.
Thanks

what's the purpose of freed? is that it's very important for any program? Thanks again :)
closed account (4z0M4iN6)
To free memory is very important:

Consider this:

char * pMyMemory = new char[100000];


A function, which does this, allocates 100 kb memory at the heap.
If the function would not free the memory, and your programm would often call this function, more and more memory will be allocated. At last your computer hasn't any memory left and your program will crash.

And people, who wrote C programs often forget this:

for example:

1
2
3
4
5
6
7
8
char * pMyMemory = new char[100000];

...

if(error) return error;
...

delete pMyMemory;


If you write a class, you don't need to take much care of delete in your function, for example:


1
2
3
4
5
6
AllocMemory Allocation(100000); // also AllocMemory Allocation = 100000 would be correct
char * pMyMemory = Allocation.pMemory;
...
if(error) return error; // don't need to free, if the destructor of class AllocMemory does this

...



But please, don't reassign your Allocation, if not neccessary, it's more tricky, than yould would think - see my post "Are these really the basics of programming in C++ with visual studio 2008?".

Don't write later:

Allocation = AllocMemory(500);

If you want to reassign your memory, you should write:

1
2
delete Allocation.pMemory:
Allocation = 500;


For doing this, you have to code an assignment operator "operator=".
Last edited on
Instead of using dadabe's buggy AllocMemory class you can use std::vector.
closed account (4z0M4iN6)
Yes, if you want to make reassignments and not only want to have a simple memory allocation.

But it depends much, what you want and which kind of memory you need.

If you want physical ram, which can be accessed by PCI boards, for example, neither std::vector nor new char[size] couldn't be used.

new char[size] was only ment as an example!

And the class isn't buggy, it was only a buggy reassignment!
Last edited on
Topic archived. No new replies allowed.