pokche pokche - 1 month ago 11
C++ Question

How to value initialize derived class?

Currently I am using

std::initializer_list<std::vector<double>>
to initialize my matrix class.

class matrix{
public:
matrix(std::initializer_list<std::vector<double>> list: row(list.size(),
col((*list.begin()).size()), matrix(list){}

private:
std::vector<std::vector<double> matrix; // I am planning to use single contiguous memory in future
};


This allows me to value initialize matrix

matrix mat = {{1,2,3},{4,5,6}};


Now I use matrix to create vector (mathematical)

class Vector: public Matrix{
Vector(std::initializer_list<double> list):Matrix(list){}
// Vector(std::initializer_list<std::vector<double>> list):Matrix(list){}

};


What I wanted to do for Vector was

Vector vec = {1,2,3};


but since I can't pass
std::initializer_list<double>
to base I am stuck with

Vector vec = {{1,2,3}};
which I don't want.

Is there any other way to handle this situation (by dropping the initializer_list and using something completely different) or should I stick with initializer_list?

I think the intializer_list does the initialization in run time, I read it from here. Is there a way where I could do the initialization in compile time?

Answer

I modified your code, so that at least it compiles. Hope it helps:

class Matrix {
public:
    Matrix(std::initializer_list<vector<double>> _list):
            row(_list.size()),  col((*_list.begin()).size()), m_matrix(_list){}

private:
    size_t row, col;
    std::vector<std::vector<double>> m_matrix; // I am planning to use single contiguous memory in future
};

class MyVector: public Matrix{
public:
    MyVector(std::initializer_list<double> _list): Matrix({_list}) {}
};

As a side not, its not good idea to use vector or list as veriable names, as these are container names in C++ STL.