First, this is the code:
#include <vector>
enum class Color
{
black = 0,
white = 1,
};
class Pixel
{
private:
Color m_color;
public:
Pixel(Color color = Color::black)
:m_color{ color }
{
}
};
class ScreenBuffer
{
private:
std::vector<Pixel> m_screenbuffer;
std::size_t m_width;
std::size_t m_height;
public:
ScreenBuffer(std::size_t width, std::size_t height)
:m_screenbuffer(width* height), m_width{ width }, m_height{ height }
{
}
};
int main()
{
ScreenBuffer main(10,10);
return 0;
}
It's a very simple screenbuffer, composed by pixels that can be either black or white.
The current ScreenBuffer constructor takes 2 parameters width and height
and initialize the m_screenbuffer vector member setting its size to width*height
and calling the Pixel constructor for each element of the vector. The current Pixel constructor, if no argument is passed, sets its m_color member to Color::black by default.
If I wanted to initialize each Pixel of the vector passing an argument, (say for this case Color::white, or using another constructor that takes more parameters), how to call THAT Pixel constructor using member initializer list from the ScreenBuffer class constructor?, how to type all those parameters needed by the Pixel constructor inside the vector constructor?
Vector constructor is m_screenbuffer(size,value)
, so I tried :m_screenbuffer(width* height,Color::white)
and it worked! but it doesnt make sense since it should expect for a Pixel object not a Color one. and...what if my Pixel constructor needed more parameters, what is the right way to pass those parameters?
I want to know the right way to do this and why and how it works so I can understand better the logic of the semantics. THANKS!
I found the answer that I was looking for in here: learncpp.com/cpp-tutorial/anonymous-objects There is a concept called anonymous objects that let me use Pixel(some_color) as an rvalue and pass it as an argument of another constructor.