Class members visibility C++

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?

Upvotes: 0

Views: 110

Answers (2)

Tareq Joy
Tareq Joy

Reputation: 362

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.

Upvotes: 0

Pablochaches
Pablochaches

Reputation: 1068

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
}

Upvotes: 2

Related Questions