I am new to C++ and recently took on the study of objective oriented programming. I wanted to write my own linear algebra module processing three dimensional vectors and 3x3 matrices. I tried to define a matrix as a class consisting of three vectors.
class vector {
public:
double n1, n2, n3;
vector (double a, double b, double c) {
n1 = a; n2 = b; n3 = c;
}
};
class matrix {
public:
vector m1, m2, m3;
matrix (vector a, vector b, vector c) {
m1 = a; m2 = b; m3 = c;
}
};
However, I am getting a compilation error:
In constructor `matrix::matrix(vector, vector, vector)':
no matching function for call to `vector::vector()'
I am guessing that the program doesnt know how to construct a matrix using the vector class i defined. However I do not understand why. If anybody could explain, i would be very grateful.
Through class conversion, one can assign data that belongs to a particular class type to an object that belongs to another class type. where '=' has been overloaded for objects of class type 'B'. Class conversion can be achieved by conversion function which is done by the use of operator overloading.
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass outerObject = new OuterClass(); OuterClass.
You need to initialize your m1,m2,m3
members by member initializer list:
matrix (const vector& a, const vector& b, const vector& c)
: m1(a),m2(b),m3(c)
Note the following:
Also, note, there is std::vector
, you may want to rename your own vector to void naming confliction and you'd better pass vector
by const reference.
Here's why this is going wrong:
Construction of an object happens in multiple phases. For your matrix class, you first need to construct all member objects and only then execute the constructor body. The important thing to realize here is that before the constructor body is entered, all member objects (in your case m1
, m2
and m3
) must have been constructed.
The problem is that the compiler cannot construct the vector
members by itself: It only knows one constructor for vector
and that one requires three double
s for construction, which it does not have. You can provide the compiler with those missing constructor arguments for vector
using the initializer list syntax, as suggested by billz's answer.
This works because the initializer list is executed during the member-construction phase of startup, which happens before the constructor-body phase.
Alternatively, provide a default constructor for vector
so that the compiler is able to automatically construct the matrix members without additional information, as suggested by Zac's answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With