pass an array of pointers to constructor initialization list?

How to pass an array of pointers to a constructor initialization list?
My failed attempt is on line 18:
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
#include <iostream>
using namespace std;

class A
{
	private:
		char c;
	public:
		A(char c): c(c) {}
		void print() { cout << c << endl; }
};

class B
{
	private:
		A* aPtrs[];
	public:
		B(A* ap[]): aPtrs(ap[]) {} // array is passed by reference
		void printArray()
		{
			aPtrs[0]->print();
			aPtrs[1]->print();
			aPtrs[2]->print();
		}
};

int main()
{
	A x('x');
	A y('y');
	A z('z');
	A* aPtrs[] = {&x, &y, &z};

	B b(aPtrs);
	b.printArray();
}


compile error:

D:\wolf\Documents\teensy\demo_MinGW>g++ array_pass4.cpp
array_pass4.cpp: In constructor 'B::B(A* const*)':
array_pass4.cpp:19:30: error: expected primary-expression before ']' token
   B(A* const ap[]): aPtrs(ap[]) {} // arrays are passed by reference
                              ^


Thank you.
Last edited on
closed account (j3Rz8vqX)
Maybe this will work for you:
1
2
3
		B(A* &ap) {} // array is passed by reference

	B b(*aPtrs);//passed an array 
Dput,
Unfortunately that didn't work:
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
#include <iostream>
using namespace std;

class A
{
	private:
		char c;
	public:
		A(char c): c(c) {}
		void print() { cout << c << endl; }
};

class B
{
	private:
		A* aPtrs[];
	public:
		B(A* &ap): aPtrs(ap[]) {} // array is passed by reference
		void printArray()
		{
			aPtrs[0]->print();
			aPtrs[1]->print();
			aPtrs[2]->print();
		}
};

int main()
{
	A x('x');
	A y('y');
	A z('z');
	A* aPtrs[] = {&x, &y, &z};

	B b(*aPtrs); //passed an array
	b.printArray();
}


compile error:
D:\wolf\Documents\teensy\demo_MinGW>g++ array_pass4.cpp
array_pass4.cpp: In constructor 'B::B(A*&)':
array_pass4.cpp:19:23: error: expected primary-expression before ']' token
   B(A* &ap): aPtrs(ap[]) {} // array is passed by reference
                       ^
Last edited on
This works:
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
#include <iostream>
using namespace std;

class A
{
	private:
		char c;
	public:
		A(char c): c(c) {}
		void print() { cout << c << endl; }
};

class B
{
	private:
		A** aPtrs;
	public:
		B(A** ap): aPtrs(ap) {}

		void printArray()
		{
			aPtrs[0]->print();
			aPtrs[1]->print();
			aPtrs[2]->print();
		}
};

int main()
{
	A x('x');
	A y('y');
	A z('z');
	A* aPtrs[] = {&x, &y, &z};

	B b(aPtrs);
	b.printArray();
}


output:
x
y
z
Last edited on
Topic archived. No new replies allowed.