سؤال

Consider class A and B. Class A is befriended by class B. Class B has a private constructor. Can class A create class B instances, or is a private constructor an indication to the compiler that the class cannot be instantiated, even by a friend class?
Here's some sample code:

class B;

class A {
    void myFunction() {
        B newBobject;
    }
};

class B {
    private:
        B() {}
    public:
        int someData;
        friend class A;
};

Also, note I'm using C++03. If it's not valid in C++03, is it allowed in C++11?

As a side question, how is the Singleton method related? Does it deal specifically with instantiating one and only one instance of an object, or is it something else?

هل كانت مفيدة؟

المحلول

Your code(more like your idea) is actually error free and valid on both C++03 and c++11.

There are 2 errors in your code however. To create an object of type B, you need to see the entire definition of B, and that means the definitions of B and A need to be exchanged.

Secondly, you need to make myfunction public, or call it from within class A.

To answer your other question.. Most singletons are implemented somewhat like this..

class Singleton{
private:

   Singleton(){}
public:
   static Singleton& GetInstance(){
       static Singleton instance;
       return instance;
   }
};

This would prevent anybody but the Singleton class (and a friend as you have discovered) from making an instance of the class, so it is easier to enforce the 1 object rule. The Singleton will be accessed as Singleton::GetInstance().

This and other possible implementations are shown at Wikipedia.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top