Dynamic memory allocation

I was studying for my exam, and I came across the following question:

How many instances of MyClass exist in memory when program execution reaches point X?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
MyClass *func1(MyClass a) {
MyClass b;
MyClass * c = new MyClass();
return c;
}
void func2(MyClass d) {
   MyClass e;
   MyClass * f = new MyClass();
   MyClass * g = func1(e);
   POINT X
   return;
}
int main() {
   MyClass h;
   MyClass * i = new MyClass();
   func2(h);
   return 0;
}


I think the answer is 5, for objects e,f,g,h, and i. However, I am not sure if an onject is instantiated if it is specified as a function parameter? For example, would the objects a,c,d be object instantiations?
It is passed by copy, so another object must be created.
So then would there be 6 instances of MyClass by POINT X?
6 by my count.
6 by my count, too.
Last edited on
jsmith and rapidcoder wrote:
6 by my count

Same here.

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
#include <iostream>
using namespace std;

class MyClass
{
public:
    static int instance_counter;

    MyClass() { instance_counter++; }
    MyClass(const MyClass &) { instance_counter++; }
    ~MyClass() { instance_counter--; }
};

int MyClass::instance_counter=0;

MyClass *func1(MyClass a)
{
    MyClass b;
    MyClass * c = new MyClass();
    return c;
}

void func2(MyClass d)
{
   MyClass e;
   MyClass * f = new MyClass();
   MyClass * g = func1(e);
   cout << MyClass::instance_counter << endl; //POINT X
   return;
}

int main()
{
   MyClass h;
   MyClass * i = new MyClass();
   func2(h);

   cout << "\nhit enter to quit..."; cin.get();
   return 0;
}
Last edited on
Thanks.
Topic archived. No new replies allowed.