Dynamic Memory is something where I seem to have problems with it since I started with C++ a few months ago.
For example, you can make a dynamic array on this way:
int* ArrayName = new int[size];
I understand this. But now I saw this:
class* ArrayName[10];
ArrayName[0] = new class2(parameters);
ArrayName[1] = new class2(parameters);
Where class 1 is the base and class2 is the derived class.
I don't really understand that anymore. How does that works? Why do you need to do it on this way? Or is there another, simpler way?
The second thing is the this-pointer. When exactly do you need to use this yourself? I see this being used like this:
ArrayName[i]->method;
Why does this work? Can someone explain this please?
My third question:
Assuming we have this now:
int* IntegerName;
If you want to access this, do you need to write:
&IntegerName = value;
or
*IntegerName = value;
The second one, right? But what with things like:
int IntegerName = 50;
(char*)&IntegerName; ?
And what if it's not an integer, but a class. How to access it's methods?
1 ) If you want a dynamic array of class2 you can just do class2 *array = new class2[ n ]; ( for this class2 must have a default constructor )
The base *pointer = new derived; thing is used for polymorphism ( http://www.cplusplus.com/doc/tutorial/polymorphism/ )
2 ) the keyword this is used in the class methods
eg:
1 2 3 4 5 6 7 8 9 10
class C
{
int x;
C func ( )
{
x = 5;
this->x = 5; // does the same as above
return *this; // returns a copy of the object from which the member function was called
}
};
int Just_int; // declare an int
int *Pointer_to_int; // declare a pointer to int
Pointer_to_int = &Just_int; // Make Pointer_to_int pointing to Just_int location ( &Just_int = Just_int's memory address )
*Pointer_to_int = 5; // set the int pointed by Pointer_to_int to 5