0

I have the following two classes.

Class A
{
   proctected:
      A(){}
};

Class B
{
    push_new_A_into_v();
    vector<A> v;    
};

The function

push_new_A_into_v();

will not compile since A's constructor is protected. To make B inherit from A will not help since the method create a completely new A(Why is protected constructor raising an error this this code?).

The reason A's constructor is protected is to make users unable to create an object of type A.

How can I make it possible for the method to work while users is still unable to create objects of type A?

Community
  • 1
  • 1
Bojack
  • 459
  • 1
  • 5
  • 18

2 Answers2

4

In addition to user2913094's answer:

If giving B full friendship just to allow construction seems unacceptable, you can add a constructor that requires a construction token, which can only be obtained by B:

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

    A(ConstructionToken const&);
protected:
    A();
};

Note that the token class is completely empty, but since only B can access its private constructor, that essentially prevents the user of invoking A's public constructor directly.

This allows for more fine-grained access control, but has the disadvantage that it requires introducing an additional constructor overload on A.

Community
  • 1
  • 1
ComicSansMS
  • 51,484
  • 14
  • 155
  • 166
  • It worked great until I needed to have A in a pair. Then class A seems to need a default constructor! – Bojack Jan 11 '15 at 17:27
2
class A {
    friend class B;
    ...
user2913094
  • 981
  • 9
  • 16
  • I heard that friend should be avoided but maybe I am wrong! If I make B a friend, then everything in class A can be private instead of protected? – Bojack Jan 09 '15 at 13:34
  • certainly consider making the constructor private if possible - since that prevents a derived class constructing an A. However a `friend` relationship is completely trusting. B would be able to see into A. If that's not desired, see the other answer - a construction token linking only the specific constructor of A to B. – Richard Hodges Jan 09 '15 at 13:52
  • @user1991779 The friend keyword breaks the access modifier by adding exceptions and purist OO programmers would advocate to avoid using it. The discussion whether using it or not would be similar to not using goto. My personal take on this is that if you know what you are doing, just use it :) – Pedrom Jan 09 '15 at 13:54