Dynamic Memory Allocation in Classes Flashcards
When declaring multiple pointers (of any type) in the same line, what do you need to do?
Include the asterisk with each pointer declaration. Also remember that any declaration that is missing an asterisk operator will be a non-pointer of that type:
MyClass * a, *b, c
a and b are MyClass pointers.
c is a normal MyClass variable
MyClass * myp1 = new MyClass;
What constructor will this call?
The default MyClass constructor.
MyClass * myp2 = new MyClass(2,3);
What constructor will this call?
A constructor with two parameters (if such a constructor exists.)
MyClass * myList = new MyClass[20];
What will this do?
Create an array of 20 MyClass objects, all of which will use the default constructor.
How would you deallocate the following array?
MyClass * myList = new MyClass[20];
delete[] myList;
What does the . operator require as its l-value?
An object name (or effective name) which serves as the calling object.
objectName.memberName
The member being called can be data or a function.
What does the arrow operator (->) need as its l-value?
A pointer to an object, which then calls member data or a member function using the object pointer as the caller.
pointerToObject->memberName
If you didn’t use the arrow operator (->), how would you call a pointer to an object as the l-value of the . operator?
By dereferencing the pointer and putting it in parentheses due to the fact that the dereference operator has lower precedence than the . operator, so the parentheses are needed in order to prioritize dereferencing before the operator calls the pointer.
(*ptr).Show();
Note that the above is equivalent to:
ptr->Show();
What syntax is easiest and works best for single object pointers to call member data and functions?
What syntax is easiest for doing the same thing with dynamic arrays?
Arrow operator is easiest for single object pointers:
ptr->Show();
Standard array syntax is easier for dynamic arrays:
mList[1].Show();
Is this legal if the content of mList[2] is an object?
mList[2]->Show();
Why or why not?
No.
mList[2] is an object, not a pointer, so it can’t use the -> operator to call a member function. The . operator needs to be used instead:
mList[2].Show();
However, if mList[2] was a pointer to an object, it would work correctly as originally written in the question.