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.
class vector
{
public:
double* p;
int n;
vector(int n0)
{
n = n0;
p = newdouble [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&)
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.
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;
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.
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 ) {}
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.)