Why do the following two usecases behave differently?
An example for a built-in type:
class Test
{
operator const char*() {
return "operator const char*() called";
}
operator char*() {
return const_cast<char*> ("operator char*() called");
// a really ugly hack for demonstration purposes
}
};
Test test;
const char *c_ch = test; // -> operator const char*() called
char *ch = test; // -> operator char*() called
Okay, everything works as it should. No, let's try it with a user-defined type:
class ColorWrapper
{
operator const Color() {
cout << "operator const Color() called" << endl;
return Color(10, 20, 30);
}
operator Color() {
cout << "operator Color() called" << endl;
return Color(11, 22, 33);
}
};
ColorWrapper cw;
const Color c_col = cw;
Color col = cw;
The situation looks identical; but now, GCC starts complaining:
error: conversion from 'ColorWrapper' to 'const Color' is ambiguous
error: conversion from 'ColorWrapper' to 'Color' is ambiguous
Am I missing something? What I'm trying to achieve here is to prevent the user from changing the color directly. If they want to change it, they must do it via the wrapper class.
Colorandconst Colorhelps with that.constversion. The reason I'm using this strange design is theColorclass was designed without inheritance in mind (no virtual methods). If I was able to inherit from it, I'd be able to use more straight-forward design.