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?
Asked
Active
Viewed 87 times
0
-
5Please show a code sample in addition to describing the problem. – cigien May 29 '20 at 18:09
-
7This is a rather strange requirement and seems anti pattern. What's the actual requirement and reasoning? – SwiftMango May 29 '20 at 18:11
-
declare the constructor `private` and then declare your `main()` as a [`friend`](https://en.cppreference.com/w/cpp/language/friend) of the class – Remy Lebeau May 29 '20 at 18:26
-
1What do you mean by an "initializer of a class"? – HolyBlackCat May 29 '20 at 18:31
2 Answers
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
-
1It 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
-