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:
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 {
^~~~~~~~~~~~~~
A conversion function to a private base class defeats the purpose of private inheritance. That's part of the reason why the standard forbids this kind of behavior:
A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it), or to (possibly cv-qualified)
void
.
If you want access to the base class you should make the inheritance public. This keeps the code readable and comprehensive for others who may have to maintain it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With