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)
-guest:;
2001-7-3(#118794@0)
yes, you can. And you could only new an object in this case.
-mrviceroy(杀人者Daniel是也);
2001-7-4(#119353@0)
what the side effect for the virtual function in class?
-guest:interview question;
2001-7-4(#119468@0)
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.
-numnum(numnum);
2001-7-5(#120563@0)
u wrong, if the constructor is private, new can't create its instance.
-blaise(blaise);
2001-7-4{184}(#119686@0)
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(numnum);
2001-7-5(#120567@0)
numnum is right
-frank2001(mouse);
2001-7-6{129}(#122877@0)
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).
-old(HH);
2001-7-15(#132969@0)
I don't think so. How to create the first one if you have only private constructor(s)?
-loafer(loafer);
2001-7-16(#133425@0)
Change the private static Singleton obj in the class declaration to static Singleton obj[3], then 3 objects can be created.
-old(HH);
2001-7-16(#133481@0)
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.
-loafer(loafer);
2001-7-16{89}(#133513@0)
. 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.
-old(HH);
2001-7-16{163}(#133531@0)
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?
-loafer(loafer);
2001-7-16(#134038@0)