Private inheritance and implicit conversion

Viewed 1873

I have a class that inherits privately from std::string, and adds some functions. I want to be able to use this class just like std::string, so I am trying to define an implicit conversion operator (operator string()). However, I keep getting inaccessible base error.

#include <iostream>
#include <string>

using namespace std;
class Test:private string {
    int _a;
    public:
    operator string() {
        return "hello";
    }
};

int main() {
    Test t;
    if(t == "hello") {
        cout<<"world\n";
    }
}

Error:

trial.cpp: In function ‘int main()’:
trial.cpp:15:13: error: ‘std::basic_string<char>’ is an inaccessible base of ‘Test’
 if(t == "hello") {
         ^

Questions:

  1. Is it a bad idea to define such a conversion? Does this break any recommended programming practices?
  2. How can I make this work?

EDIT: Clang was more helpful

trial.cpp:8:5: warning: conversion function converting 'Test' to its base class 'std::basic_string<char>' will never be used
    operator string() {
    ^
trial.cpp:15:8: error: cannot cast 'Test' to its private base class 'basic_string<char, std::char_traits<char>, std::allocator<char> >'
    if(t == "hello") {
       ^
trial.cpp:5:12: note: declared private here
class Test:private string {
       ^~~~~~~~~~~~~~
3 Answers
Related