Answers/Solutions to Exercises in Chapter 8, Exercise 2

E2: Consider a C++ class:

class A {
    public:
        B* b;
        A() { b = new B(1,2); }
        ~A() { delete b; }
        void* operator new(size_t size) {
            ...
        }
};//end class A

When an object of class A is being constructed, which new is being used to create the object of class B: the class-A
specific new, or the class-B specific new, or the global new ?

A2: Of course, the object B inside the object A will be created using class-B specific new (if there is such), if not, it will be created by the global new. You can try it with the following program:

class B
{
    public:
	int p;
	B(int i,int j) { p=i+j; }
	void* operator new(size_t size) {
		printf("B-new\n");
		// create p
		int *x;
		x = new int;
		printf("object B created at address %d\n",x);
		// return address of p
		return x;
	}

};

class A {
    public:
        B* b;
        A() { b = new B(1,2); }
        ~A() { delete b; }
        void* operator new(size_t size) {
           printf("A-new\n");
		   // create b
		   B** x; 
		   x = new (B*);
		   printf("object A created at address %d\n",x);
		   // return address of b
		   return x;
        }
};//end class A

int main()
{
	A* a1;
	a1 = new A();
	printf("a1 points to %d\n",a1);
	printf("address of a1->b=%d,value of a1->b->p=%d\n",a1->b,a1->b->p);
	return 0;
}

This program will produce the following output:

A-new
object A created at address 4391072
B-new
object B created at address 4391024
a1 points to 4391072
address of a1->b=4391024,value of a1->b->p=3

Back to Answers/Solutions Index                          Back to Answers/Solutions for Chapter 8 Index