×

Loading...

Topic

This topic has been archived. It cannot be replied.
  • 工作学习 / IT技术讨论 / Can I write constructer as private in c++, if I can who can access it ? (This my interview question, continue)
    • yes, you can. And you could only new an object in this case.
      • what the side effect for the virtual function in class?
        • the only side effect I know of is that if you declare a virtual function , the calss size will be increased(probably by 4) , because the compiler has to insert a virtual table pointer in the class.
      • u wrong, if the constructor is private, new can't create its instance.
        constructor be private is meanful, friend function/class can create it. that's the way to avoid others(ur lib user) create the instance of class which you think they shouldn't do so.
        • yeah, in addition, the class itself can call this private constructor too, it's useful when you declare a static member of the class itself.
        • numnum is right
          You can create only ONE instance of the class by using private constructor. And in Design Patten, this is called Singleton Class.
          • You can create a number of instances of the class which has only private constructor(s).
            • I don't think so. How to create the first one if you have only private constructor(s)?
              • Change the private static Singleton obj in the class declaration to static Singleton obj[3], then 3 objects can be created.
                • what can you do with such a class? it only can be used as an encapsulated static functions set working on static members. In fact, it's not like a class, just a period of static codes, no, only some constants.
                  . Private construtor is very useful when you want to transfer class object as a parameter
                  • It can be used to limit the number of instances of a singleton class to be created. For example “your” singleton class can has only one instance, “my” singleton class can has a fixed number of instances.
                    class Singleton {
                    public:
                    /* Other public members will be added here */

                    private:
                    /* Other private members will be added here */
                    static Singleton obj[3];
                    };
                    • still i can't understand how to use it without any public constructor. You can only use the static members. what's the purpose with such kind of classes?
      • 把你的class girl增加一个这样的构造函数,然后跟踪一下boy::suit,你就清楚了。哈哈,我就看了两条Post,都有你。看来你是这里的常客。我用朋友的UserID上来的,回头我也注册一个。
    • 自己拷贝自己的时候用
    • is the singleton pattern