Search code examples
c++data-hiding

How is the usage of constructors an implementation of data-hiding?


I know what constructors are used for, and kinda know what data hiding means.... found absolutely no link among the two (im a dimwit, sedd).... please help?


Solution

  • I'd have argued that ctors can be used as a form of RAII. Essentially we can initialise an internal (private) variable via a constructor, and that variable can now be made to be inaccessible outside of the class.

    class Foo
    {
    public:
      Foo(int i)
        : m_i(i) {} //< only place we init variable
    
    private:
      int m_i; //< we cannot access this var
    };