0

I need to make the initializer of a class invisible for the child classes, but visible for the main(). How can I do it? The only way I see is to make it PUBLIC, but it will be inherited to the child classes. Any ideas?

2 Answers2

2

You can make it private and add main as a friend

class A {
private:
    A() {}
public:

friend int main(void);
};

int main(void) {
    // Your code
}
Pablochaches
  • 968
  • 10
  • 25
  • 1
    It seems a bit wrong to give full access for `main` to all of the internals of this class. I don't think that there is a good solution for this question – Kerek May 29 '20 at 19:20
0

Making the initializer private (cannot access the initializer even in main), there are many design patterns you can follow for solving your problem. One of the design pattern is Singelton. The example is given below:

#include <iostream>

using namespace std;

class A{
    private:
    static A *single_instance;

    //private constructor, cannot be inherited
    A(){

    }

    public:
    //for getting access in main
    static A *getInstance() {
        if (single_instance==NULL){
            single_instance = new A();
        }
        return single_instance;
    }

    void print() {
        cout<<"I'm from A";
    }


};
//initializing with NULL
A *A ::single_instance=NULL;

class B:A {
    //not access to the constructor

    //but access to getInstance()
};

int main()
{
    //now you can access it in main
    A *obj = obj->getInstance();
    obj->print();
    return 0;
}

Note that, this design makes sure, only one instance can be created from your class.

Tareq Joy
  • 342
  • 3
  • 12
  • This isn't a good use of Singleton, but if you find a case where Singleton is a good fit, Prefer to use a [Meyers Singleton](https://stackoverflow.com/a/1008289/4581301) as it's much easier and much less likely to blow up in your face when things get more complicated. – user4581301 May 29 '20 at 19:01
  • Yes! I see! Thank you. – Tareq Joy May 29 '20 at 19:02