Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private inheritance and implicit conversion

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 {
       ^~~~~~~~~~~~~~
like image 694
SPMP Avatar asked Mar 04 '16 21:03

SPMP


Video Answer


1 Answers

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.

like image 184
David G Avatar answered Oct 18 '22 19:10

David G