tariq zafar
tariq zafar

Reputation: 659

Private inheritance usage from client

I had a question related to private inheritance in C++. My question is based on a reference related to this page here. (Under the heading "But What If We Do Need To Inherit?")

The case is point is I declare a base class with a public virtual function. Then I inherit base class under private inheritance and name it derived class. this is shown as below

    class base {
            public:
            base() {}
            virtual ~base() {}
            virtual void func_1() {
                cout<<"base func1"<<endl;
            }
            void func_t() {
                cout<<"base funct"<<endl;
                func_3();
            }
            private:
            void func_3() {
                cout<<"base func3"<<endl;
                func_1();
            }
        };

class derived: private base {
public:
    derived() {}
    ~derived() {}
    virtual void func_1() {
        cout<<"derived func1"<<endl;
    }
};

base* b = new derived;
b->func_t();

The above statements give error that base is an inaccessible base of derived. What do I do if I want to call the func_1 as part of above function call function of the derived?

Upvotes: 0

Views: 59

Answers (2)

utnapistim
utnapistim

Reputation: 27365

Since you inherit base as a private base class, this means that all public members of base (including base::func_1) will be private in derived. The compiler will complain when you declare derived::func_1 as public.

If you need derived::func_1 as public, then you should inherit base publicly. If you do not need it to be public, then you should declare derived::func_1 as being private.

Upvotes: 1

Jan Herrmann
Jan Herrmann

Reputation: 2767

private indicates that names and members are not accessible from outside. The conversation to a private base class is one occourrence. You can simply wrap this conversation into a member function to let it work:

class derived
  : private base {
public:
    // other stuff

    base* get_base() {
        return this;
    }
};

derived* d = new derived;
base* b = d->get_base();
b->func_t();

Upvotes: 1

Related Questions