#33 Non-const in copy ctor's signature breaks the compilation


Hi! I faced an issue while trying to return BMP instance by value. The code is as follows:

BMP Player::GetCurrentFrame()
BMP frame;
// Some processing here
return Frame;

// The line below breaks the compilation under certain compilers (e.g. MingGW used in DevCPP)
BMP frame = player->GetCurrentFrame();

I looked into sources and discovered that copy ctor's signature is a kind of non-standard hence the compiler error:

// Doesn't work - compiler fails to find the copy ctor
BMP( BMP& Input );
// Should be: BMP(const BMP& Input );

I've tried to merely change the signature but this lead to "xxx discards const qualifier" error since the methods called on the source instance ("Input") are not marked as const. At this point I had 2 choices:

1) Make a dirty hack and create a proxy copy ctor which casts away constness and calls the original copy ctor:

BMP::BMP(const BMP& Input)

2) Go further and add const to all the methods having getter semantics:

int TellBitDepth( void ) const;
int TellWidth( void ) const;
int TellHeight( void ) const;
int TellNumberOfColors( void ) const;
int TellVerticalDPI( void ) const;
int TellHorizontalDPI( void ) const;
RGBApixel* operator()(int i,int j) const;
RGBApixel GetPixel( int i, int j ) const;
RGBApixel GetColor( int ColorNumber ) const;

The first approach worked fine, the second one revealed that in TellHorizontalDPI() (now const) certain members are mutated. In order to handle that, I marked them accordingly:

mutable int XPelsPerMeter;
mutable int YPelsPerMeter;

This finally solved copy ctor problem.


Log in to post a comment.