Class using another class (that has allocatable array)

Apr 21, 2011 at 6:26pm
Hi all,
I try to build a call using another class as member variables as below. Because the previous class (vector) need an allocatable array, I have to write a constructor (vector). But the point is when I want to construct the second class (supervector), the member data A need to be initiated by the supervector constructor, that reads the size of A. The code below can not work, can we declare the member variable so that is constructed only when supervector is called?
Thank you very much for your comments.
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
class vector
{
public:
	double* p;
	int n;
	vector(int n0)
	{
		n = n0;
		p = new double [n];
	};
	
};

class supervector
{
	vector A;
	int n;
public:
	supervector(int n0)
	{
		n = n0;
		A = vector(n);
	};
};


int main()
{
	supervector B = supervector(5);
};

Which the error is:
1
2
3
4
check.cpp: In constructor ‘supervector::supervector(int)’:
check.cpp:39: error: no matching function for call to ‘vector::vector()’
check.cpp:25: note: candidates are: vector::vector(int)
check.cpp:21: note:                 vector::vector(const vector&)

Apr 21, 2011 at 6:31pm
supervector(int n0) : n(n0), A(n0) { /*whatever else you want to do*/ }
It's called initializer list. It's a way to call member's constructor from the class constructor. Note that integers and other base types too can be initialized this way.
Apr 21, 2011 at 6:31pm
The error is pointing out that you do not have a default constructor for your vector class or your supervector class. That is why you are getting the error on line 16 where you have vector A;
Apr 21, 2011 at 6:49pm
Thank you,
@kooth, yes, I am trying to avoid that.
The initializer list works, thanks. I put here a link that explains a bit more, maybe someone else needs too.
http://www.cprogramming.com/tutorial/initialization-lists-c++.html
Apr 25, 2011 at 6:32am
Hi all,
The initiation list works for variables, but if now I want to work with pointers (ie. ,in the second class, supervector, which is vector * pA), can I call the user specified constructors for the first class (vector.)?
Thank you for your helps.
Apr 25, 2011 at 8:19am
If you only have a pointer, then a constructor will be called whenever you use new.
You can still put it in an initializer list: supervector() : pA( new vector ) {}
Apr 25, 2011 at 8:55am
Thank you very much, hamsterman, that works for the single vector pointer.
Can I also create an array of objects with non-defaut constructors somehow, like: pA = new vector (n) [5]?
(The above code doesn't work, just to illustrate the idea.)
Apr 25, 2011 at 10:17am
No, sadly.
Apr 25, 2011 at 10:58am
Yeah, thanks, once more :-)
Topic archived. No new replies allowed.