0

For Example:

class A{ int b; A *a1; A *a2; A(int c):b(c), a1(c), a2(c) {} } 

I thought this was the way, but it doesn't compile. Is there a way to do this, or is it necessary to always use dynamic allocation? thanks

1
  • It's not clear what you're trying to do. In this code, c is an integer. What do you think setting a variable of type A* to an integer is going to do? Commented Jan 16, 2012 at 4:44

3 Answers 3

1

You could simply initialize the pointers to null.

class A{ int b; A *a1; A *a2; A(int c):b(c), a1(NULL), a2(NULL) {} } 

(Note that if it complains about NULL not being defined, #include <cstddef>)

Or not initialize them at all.

class A{ int b; A *a1; A *a2; A(int c):b(c) {} } 
Sign up to request clarification or add additional context in comments.

Comments

1

It's not clear what you're trying to do, but you certainly can do it:

class A{ int b; A *a1; A *a2; A(int c, A* pa1, A* pa2):b(c), a1(pa1), a2(pa2) {} } 

Which you can call like this:

A m1(1, NULL, NULL); A m2(2, NULL, NULL); if(something()) { A m3(3, &m1, &m2); // do stuff with m3 } 

Just be careful. If m1 or m2 go out of scope before m3, then m3 will be left with pointers that point to random garbage.

1 Comment

"It's not clear what you're trying to do, but you certainly can do it" For better or worse, this is generally the case in questions with the C++ tag...
1

If you don't want to initialise the pointers to nullptr (NULL or 0 pre-C++11) like this:

class A { A(int c) : b(c), a1(), b1() { } int b; A* a1, *a2; }; 

then either the object you make the pointer point to has to exist in some outer scope so that it will live at least as long as the object that contains the pointer, or you have to use new.

You could accept an A* to set the pointers to:

class A { A(int c, A* aptr) : b(c), a1(aptr), a2(aptr) { } ... }; 

(You can't use a reference for this because that would make an A a requirement for an A, an impossible condition to satisfy. You could make an additional constructor that accepted a reference though.)

In your example, you are trying to use an int to initialise a pointer which won't work. Also, if you create an object in your example (via new or whatever), you will run out of memory because each A you allocate will allocate two more As and that cycle will continue until you run out of memory.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.