Initialization list with pointer

I want to initialize an object A in class B but I want to initialize the object as a pointer. For some reason the code doesn't call the constructor for class A.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 class A
{
 protected;	
 int x;
 int y ;
public:
 A()//constructor
 {    
   x=25;
   y=17;   
   cout << "x: " << x << endl;
   cout << "y: " << y << endl;
 }
};

class B
{
protected:
	A*a;
public:
	B():a(NULL){}
};

The code works fine if I initialize an object of as " A a", but I want to assign an of objects of class A on the heap.

Last edited on
Pointers never auto-construct objects; you must do that explicitly.

In your case, you are explicitly assigning a value of NULL to your pointer-to-an-A. Construct an A and assign its address instead:

B(): a(new A) { }

Don't forget to delete (free) the A in B's destructor!

Hope this helps.
Thank you!!!!!!!!!!!!!!!!!!!!!!!!!!
Topic archived. No new replies allowed.