开发者

c++ language oops

Why开发者_JAVA百科 do we declare constructor's as public?


Constructors are the way objects are created. If your constructor were not public, then it couldn't be used to construct a new object from outside the class.

Note that sometimes a non-public constructor is useful, for example:

class foo
{
public:
    static foo make_foo(int i)
    {
        // only functions of foo can use that constructor,
        // because it's private; return a foo
        return foo(i);
    }

private:
    foo(int i) { /* construct */ }
};

Now foo can only be created via the function make_foo, for whatever reason.


In the below code line, initialization should take place via constructor. If the constructor is private in this case, how is it going to be accessed outside the class scope. Moreover, foo::foo(int num) is going to be called by default while instantiation of obj.

foo *obj = new foo(5);


If you don't you will not be able to construct the object from other objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜