cpp

Can I hide the type?

saitoatsushi

齊藤敦志

Posted on November 16, 2017

Can I hide the type?

Private member is not accessible from outer the class. Private member is inner only unless provide indirect method by pointer or reference.

And I can specify private for type.

For example,

#include <iostream>

class foo {
private:
  class bar {};
public:
  static bar make_bar(void) {
    return bar();
  }
  static void print_bar(bar) {
    std::cout << "bar" << std::endl;
  }
};
Enter fullscreen mode Exit fullscreen mode

I hope hide foo::bar. I do not want you make objects of foo::bar type.

In C++11 and later, you can use private types with auto or decltype.

int main(void) {
  foo::make_bar(); // OK
  foo::print_bar(foo::make_bar()); // OK
  foo::bar x = foo::make_bar();    // Error : foo::bar is private
  auto x = foo::make_bar();        // OK : You can use `auto` in C++11 and later
  decltype(foo::make_bar()) y = foo::make_bar(); // OK : You can use `decltype` in C++11 and later

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Is there way to hide the type?

💖 💪 🙅 🚩
saitoatsushi
齊藤敦志

Posted on November 16, 2017

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related