Let’s say I have a
class A
{
int A1;
void Af();
};
Then I do:
A hA;
A* pA = new A();
now, hA is an object in the stack; I can use
hA.A1 = 52 // for example
but pA just points to class A, how is that useful or handy? (any examples please?)
second issue:
when I did A* pA = new A(); did I allocate anything in the heap? was there any malloc() in the background? if not, then why not? and how come int *p_array = new int[5] will allocate memory in the heap of 5 ints and not A* pA = new A()?
leads to a compiler error. The correct way of defining a variable “on the stack” is
In some place in the memory, you have an object of type A, and pa points to it. If you want to set the A1 member of that object to 52, you write
The why is it useful part is not a real question.
Yes, you did.
newdoes two things: it allocates memory and invokes the constructor.That is unspecified, but in many implementations
newis implemented viamallocThis, sir, is also a compiler error. What you meant was
This is the
operator new[]which allocates arrays on the heap and calls constructors if necessary (in case of ints it isn’t).