Passing Pointer Arrays

I wrote this a while ago... how does it work in a data sense?
Like what is the computer doing in terms of initializing and passing variables?
thanks.
sorry for any newbie mistakes, just got back into cpp from haskell.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <string>

class Animal
{
public:   
    void eat();
};

void Animal::eat()
{
    std::cout << "yum" << std::endl;
}

class Moose : public Animal
{
public:
    void moo(std::string noise);
};

void Moose::moo(std::string noise)
{
    std::cout << noise << std::endl;
}

void graze(Moose *p, int max)
{
    
    for(int i = 0; i <= max; i++)
    {
        p->eat();
    }
    
    p->moo("moo");
}

int main()
{
    Moose* pack;
    pack = new Moose [5];

    graze(pack, 5);

    return 0;
}
Last edited on
new Moose [5]
Set aside on the heap sizeof(Moose) * 5 bytes. We'll say this is an array of 5 elements of type Moose.

pack =
Store in pack the address of the first element of the array.

graze(pack, 5);
Without getting into too much detail about the low level operations, main() will put 5 and the address contained in pack somewhere where graze() will know where to find them, then will hand over control to graze().

p->eat()
In your particular program, you don't use any polymorphism, so the compiler will transform the definition of Animal::eat() to void Animal::eat(Animal *) and will transform this call to eat(p). After this, it's a normal function call with parameter passing.

p->moo("moo")
More or less same as above, but with moo(p, "moo").
"moo" is a string literal. Using a string literal anywhere where it's allowed does two things:
* First, it instructs the compiler to set aside on the executable, space for the 4 byte array {'m', 'o', 'o', 0}.
* Second, it instructs it to replace the usage of the string with a pointer to the array.
All string literals are pointers, so you can do with them anything you can do with pointers, such as "moo"[1] == 'o'.

There are some details I glossed over because they would have lengthened this post several times without adding much that was relevant to your question, but I hope it was informative enough.
Thanks a lot!
Topic archived. No new replies allowed.