Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Public member without inheritance

I have a base class which looks something like this:

class Base
{
public:
  typedef std::shared_ptr<Base> ptr_t;
  typedef std::weak_ptr<Base> wptr_t;

  enum class Type { foo, bar, baz };

  Type x;
  // ...
};

I'd like those internal types to be public so that I can do stuff like Base::ptr_t my_ptr(new Base); and so on. But if I make a new class like this...

class Derived : public Base
{
  // ...
};

unfortunately, Derived::ptr_t is still a Base pointer. I'd like Derived to publicly inherit x from Base, but not inherit ptr_t,wptr_t, or Type. For example

Derived a;
a.x = Base::Type::foo; // this should work
a.x = Derived::Type::foo; // but I want this to fail

Is this possible, perhaps though some magic use of friend or virtual or something like that?

like image 771
karadoc Avatar asked Feb 22 '26 08:02

karadoc


1 Answers

Simply override the type:

class Derived {
  typedef int Type;
};

It will not allow the use of Derived::Type (as it's private as well as typedefed)

like image 195
iammilind Avatar answered Feb 24 '26 20:02

iammilind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!