I have written this code. It is giving no compile time errors but a runtime error. Can you please tell me what is wrong with this code?
It is giving this runtime error -> strap info: vpid 1: terminated with signal 11
#include <iostream>
class Color
{
public:
static Color White, Black, Red, Green, Blue;
unsigned char red, green, blue;
static void static_Color();
Color(unsigned char _red
, unsigned char _green
, unsigned char _blue)
: red(_red), green(_green), blue(_blue)
{
static_Color();
}
Color()
{
static_Color();
}
};
Color Color::White, Color::Black
, Color::Red, Color::Green, Color::Blue;
void Color::static_Color()
{
static bool called_before = false;
if(called_before)
return;
Color::White = Color(255, 255, 255);
Color::Black = Color(0, 0, 0);
Color::Red = Color(255, 0, 0);
Color::Green = Color(0, 255, 0);
Color::Blue = Color(0, 0, 255);
called_before = true;
}
int main()
{
std::cout << (int) Color::Red.red;
}
A needed feature static constructor.
Color
) to code:static Color white={255,255,255};
and did you compile withg++ -Wall -Wextra -g
then use the GDB debugger ? – Unprofitablestatic_color
is called recursively until stack overflow. – FripperyColor Color::White
is a call to the Color constructor, which callsstatic_Color()
, which then calls the Color constructor 5 more times. Each of them then callsstatic_Color()
again. Only ends when running out of memory for the calls. – Controllerconstexpr
here that can be used instead? – ReinerColor
values inside theColor
class. You cannot do that because the class is not fully known to the compiler until after the};
at the end. – Controllermain
to initialize your library, it seems like a bit of a failure. Can't you define the constantColor
values outside theColor
class like I showed? You then have a header only library that doesn't require a call to any function. – Gravelblindinline
d variable will be linked ot the same variable. You can print the addresses of the pre-definedColor
s in different translation units and you'll see that they are the same in all of them. – Gravelblind