Link to home
Start Free TrialLog in
Avatar of meow00
meow00

asked on

protected or private constructors ....

Hi C++ Experts,

   Is there any specific reason that we want to make the constructors private of protected ? In either case, how do we create objects of the class ? Is that trut that we can not use "A a ;" or
"new A" to create objects in these two cases ???
   Thanks.
SOLUTION
Avatar of Dexstar
Dexstar

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of meow00
meow00

ASKER

I see ....... so is that true we can construct a Base object (using the protected or private constructor) from it's friend class ? Is this something good to do ? or better not do it ?

thanks.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> Is there any specific reason that we want to make the constructors private of protected ?

Yes there is. A protected constructor can only be called from within a derived class. This is usefull if you have a base class that you want to inherit from but that you do not want an instances of it to be created explicitly. For example,

#include <iostream>
#include <iomanip>

using namespace std;

class test1
{
    protected:
        test1() { cout << "test1 constructor called." << endl; }
        ~test1() { cout << "test1 destructor called." << endl; }
};

class test2 : test1
{
    public:
        test2() { cout << "test2 constructor called." << endl; }
        ~test2() { cout << "test2 destructor called." << endl; }
};

int main()
{
    test2 t;

    return 0;
}

-- output --
test1 constructor called.
test2 constructor called.
test2 destructor called.
test1 destructor called.

Take notice that the constructor in the base class is called before the constructor of the derived class and that conversly, the derived class' destructor is called before the base class' destructor.

As for private constructors, you can use them to create a singleton class. That is, a class of which there can only be instance of at any one time. This is a rather rare circumstance where you need to have only one instance of the class in existence. You do this by making the constructor private. You then have a static member function that returns a reference to the only instance of the class. If a class instance does not exist, the function creates one.

Cheers!
Exceter
Whoa...  Never assisted myself before!  Cool!  :)