private constructors

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Preets

    private constructors


    Can anyone explain to me the exact use of private constructors in c++ ?

  • ehilah

    #2
    Re: private constructors

    Preets ha scritto:[color=blue]
    > Can anyone explain to me the exact use of private constructors in c++ ?
    >[/color]
    For example for implement singleton pattern

    Comment

    • dan2online

      #3
      Re: private constructors


      Preets wrote:[color=blue]
      > Can anyone explain to me the exact use of private constructors in c++ ?[/color]

      If you write a singleton class in C++. you will need to play some
      tricks make all constructors private, including default, copy and
      assignment operators.

      Go to http://msdn.microsoft.com/msdnmag/issues/03/02/CQA/
      to find an example of singleton class.

      Comment

      • Preets

        #4
        Re: private constructors

        can a class derive from singleton class ? And, can any number of
        instances of that derived class be created ?

        Comment

        • Amal P

          #5
          Re: private constructors

          Basic idea is that if you are making constructor private you will not
          be able to create object of that class externaly. It is usefull in many
          cases. singleton pattern is only one among them...

          Comment

          • Preets

            #6
            Re: private constructors


            a class can derive from a singleton class if the singleton's
            constructor is protected but if it is private then ? and what about the
            number of instances of the derived class ? will that be also one only ?

            Comment

            • Amal P

              #7
              Re: private constructors

              If the constructor is private then also you can derive with one
              technique. You can make the class to be derived as a friend of class
              which's constructor is private.

              Comment

              • Oren

                #8
                Re: private constructors

                Preets wrote:[color=blue]
                > can a class derive from singleton class ? And, can any number of
                > instances of that derived class be created ?[/color]

                You can check "More effective C++ by Scott Meyers" 'Item 26: Limiting
                the number of objects of a class' for a discussion about singletons and
                singletons as base classes.

                But singleton is only one of the uses of private Constructors (and the
                most famous one, I suppose). there are some other uses such as
                prohibiting the instantiation of object for a class (if you want to
                facilitate only the use of it's static properties) or forcing the use
                of what is called the "virtual constructor" pattern.

                Comment

                • Imre Palik

                  #9
                  Re: private constructors => singleton

                  "dan2online " <danielhe99@gma il.com> writes:

                  Hi,
                  [color=blue]
                  > Preets wrote:[color=green]
                  > > Can anyone explain to me the exact use of private constructors in c++ ?[/color]
                  >
                  > If you write a singleton class in C++. you will need to play some
                  > tricks make all constructors private, including default, copy and
                  > assignment operators.[/color]

                  Could you explain the reasons why would somebody write a singleton class in
                  C++ instead of using the good old C-style singleton pattern?

                  The advantages of the C-style singleton (file-local data with public
                  interface) are better information hiding, and built in compiler firewall.
                  But what are the advantages of the singleton class?


                  Comment

                  • mlimber

                    #10
                    Re: private constructors

                    Preets wrote:[color=blue]
                    > Can anyone explain to me the exact use of private constructors in c++ ?[/color]

                    Besides singletons and the virtual constructor idiom (see
                    http://www.parashift.com/c++-faq-lit....html#faq-20.8)
                    that have already been mentioned, private constructors can be used to
                    disable the implicitly generated copy constructor (and assignment
                    operator) if the class is noncopyable. A singleton holder class itself
                    often uses this feature, e.g.:

                    template<class T>
                    class Singleton
                    {
                    public:
                    static T& Instance();
                    private:
                    // Disabled functions
                    Singleton();
                    Singleton( const Singleton& );
                    Singleton& operator=( const Singleton& );
                    Singleton* operator&();
                    ~Singleton();
                    };

                    template<class T>
                    T& Singleton<T>::I nstance()
                    {
                    static T myObject;
                    return myObject;
                    }

                    class C
                    {
                    public:
                    void DoSomething() {/*...*/}
                    private:
                    friend class Singleton<C>;
                    C() {/*...*/}
                    ~C() {/*...*/}

                    // Disabled functions for singleton usage
                    C( const C& );
                    C& operator=( const C& );
                    C& operator&();
                    };

                    typedef Singleton<C> theC;

                    void Foo()
                    {
                    theC::Instance( ).DoSomething() ;
                    }

                    Also, a protected constructor can be used to enforce proper
                    initialization, especially in the case that the constructor needs to
                    call a virtual function. This is generally superior to forcing the user
                    to call an Init() function, which can easily be forgotten, leaving the
                    object uninitialized. This example is drawn from Sutter and
                    Alexandrescu's _C++ Coding Standards_ (Item 49):

                    class B // Hierarchy root
                    {
                    protected:
                    B() { /*...*/ }

                    // Called right after construction
                    virtual void PostInitialize( ) { /*...*/ }

                    public:

                    // Interface for creating objects
                    template<class T>
                    static std::auto_ptr<T > Create()
                    {
                    std::auto_ptr<T > p( new T );
                    p->PostInitialize ();
                    return p;
                    }
                    };

                    // A derived class
                    class D : public B { /*...*/ };

                    // Creating an initialized D object
                    std::auto_ptr<D > p = D::Create<D>();

                    Cheers! --M

                    Comment

                    • godescbach

                      #11
                      Re: private constructors =&gt; singleton

                      On 20 Apr 2006 12:49:55 +0200, "Imre Palik"
                      <firstname.last name.ext@automa tion.siemens.co m> wrote:
                      [color=blue]
                      >"dan2online " <danielhe99@gma il.com> writes:
                      >
                      >Hi,
                      >[color=green]
                      >> Preets wrote:[color=darkred]
                      >> > Can anyone explain to me the exact use of private constructors in c++ ?[/color]
                      >>
                      >> If you write a singleton class in C++. you will need to play some
                      >> tricks make all constructors private, including default, copy and
                      >> assignment operators.[/color]
                      >
                      >Could you explain the reasons why would somebody write a singleton class in
                      >C++ instead of using the good old C-style singleton pattern?
                      >
                      >The advantages of the C-style singleton (file-local data with public
                      >interface) are better information hiding, and built in compiler firewall.
                      >But what are the advantages of the singleton class?
                      >[/color]

                      One reason you might want to use a singleton is to inherit behaviour
                      from another class.

                      Perhaps you want to group a one or more objects into one singleton to
                      ensure only one instance for a particular program. The classes that
                      define these objects are not singletons because they can have more
                      that one instance in other programs.

                      IMO, it is best to group data and the functions that operate on it in
                      a class. This takes information hiding a step further by putting the
                      data and its functionality into class. All access must go through the
                      class. Not sure what you mean by 'compiler firewall' or how using the
                      C-style has any advantage over a class singleton in terms of the
                      compiler.

                      Clients of a singleton class don't really know or care if the class is
                      a singleton. It does not impact the interface. Using the C-style
                      singleton your public interface doesn't need a reference to the object
                      passed in because you interface knows there's only one instance with
                      which to work. So someone looking at youi code can tell if a group of
                      functions operating on some data are operating on only one instance of
                      that data. The class singleton is better at hiding this fact. But
                      this is rather subjective in any case.

                      Tom

                      Comment

                      • Imre Palik

                        #12
                        Re: private constructors =&gt; singleton

                        godescbach <g.o.d.e.s.c.b. a.c.h@yahoo.com > writes:
                        [color=blue]
                        > On 20 Apr 2006 12:49:55 +0200, "Imre Palik"
                        > <firstname.last name.ext@automa tion.siemens.co m> wrote:
                        >[color=green]
                        > >"dan2online " <danielhe99@gma il.com> writes:
                        > >
                        > >Hi,
                        > >[color=darkred]
                        > >> Preets wrote:
                        > >> > Can anyone explain to me the exact use of private constructors in c++ ?
                        > >>
                        > >> If you write a singleton class in C++. you will need to play some
                        > >> tricks make all constructors private, including default, copy and
                        > >> assignment operators.[/color]
                        > >
                        > >Could you explain the reasons why would somebody write a singleton class in
                        > >C++ instead of using the good old C-style singleton pattern?
                        > >
                        > >The advantages of the C-style singleton (file-local data with public
                        > >interface) are better information hiding, and built in compiler firewall.
                        > >But what are the advantages of the singleton class?
                        > >[/color]
                        >
                        > One reason you might want to use a singleton is to inherit behaviour
                        > from another class.[/color]

                        I'm not sure if it is meaningful to apply the Liskov substitution principle
                        to singletons. But anyway, you can easily hide the singletonness behind an
                        ordinary class.

                        I mean something like this:

                        // singleton.H
                        // includes, no need to include the definition of foo here.
                        struct singleton_inter face
                        {
                        singleton_inter face();
                        ~singleton interface();
                        void fiddle_with_it( );
                        void set_fubar(fubar fb);
                        // ...
                        };

                        // singleton.C
                        // includes
                        static fubar fb_;
                        static foo bar_;
                        // other file-scope data

                        void
                        singleton_inter face::fiddle_wi th_it()
                        {
                        // play with the file scope data
                        }

                        void
                        singleton_inter face::set_fubar (fubar fb)
                        {
                        fb_ = fb;
                        }

                        // other methodes

                        In this case you have an ordinary C++ class (but w.o. data members), that
                        still behaves as if it would be a singleton. So if you need a class
                        because you have to implement a prescribed interface, that is no excuse for
                        those pesky get_instance() methods ;-)
                        [color=blue]
                        > Perhaps you want to group a one or more objects into one singleton to
                        > ensure only one instance for a particular program. The classes that
                        > define these objects are not singletons because they can have more
                        > that one instance in other programs.[/color]

                        This is simple containment. You can easily take care of it with file scope
                        data
                        [color=blue]
                        > IMO, it is best to group data and the functions that operate on it in
                        > a class. This takes information hiding a step further by putting the
                        > data and its functionality into class. All access must go through the
                        > class. Not sure what you mean by 'compiler firewall' or how using the
                        > C-style has any advantage over a class singleton in terms of the
                        > compiler.[/color]

                        Even better information hiding :-) That is, being polite, and not showing
                        the private parts of the class on the interface. With C-style singleton,
                        you only need the headers defining the types used by the implementation
                        (i.e., private data), to compile the implementation file. They are totally
                        unnecessary when compiling user code.
                        [color=blue]
                        > Clients of a singleton class don't really know or care if the class is
                        > a singleton. It does not impact the interface.[/color]

                        You have to get a reference to the singleton from somewhere. This will
                        lead to lines like this:

                        newbar = foo:get_instanc e().fornicate(b ar);

                        I would consider this as an impact on the interface.
                        [color=blue]
                        > Using the C-style
                        > singleton your public interface doesn't need a reference to the object
                        > passed in because you interface knows there's only one instance with
                        > which to work.[/color]

                        This is not necessarily true. Especially if you have the class-like
                        interface described above, which could be abused to hold an instance ID,
                        that is used to as an index to e.g., some file local container.
                        [color=blue]
                        > So someone looking at youi code can tell if a group of
                        > functions operating on some data are operating on only one instance of
                        > that data. The class singleton is better at hiding this fact. But
                        > this is rather subjective in any case.[/color]

                        Sorry, but I can't really get this part. Could you explain?

                        ImRe

                        Comment

                        • Lyell Haynes

                          #13
                          Re: private constructors

                          >> Can anyone explain to me the exact use of private constructors in c++ ?

                          Sure. There are a few good uses for declaring a constructor as private.
                          One of those is being able to tightly control the creation mechanism of
                          instances of the class (The singleton pattern is a specific example of
                          this).

                          Using another example, let's say you have a class that is only able to
                          use a particular memory allocation algorithm. You could declare the
                          constructor as private and provide a static "create" method on the
                          class (which is still able to call the private constructor) that
                          handles creating an instance of your class using that special
                          allocation method. All clients of the class would only be able to
                          create the object through this static function and wouldn't be able to
                          create an instance on the normal stack or heap, thereby limiting their
                          chances of misusing the class.

                          Hope that answers your question.

                          Lyell

                          Comment

                          Working...