Rajeev Mehta
Rajeev Mehta

Reputation: 659

Publicizing a constructor in private inheritance

During private inheritance the public member variable or member functions of Base class can be assigned back the public access specifier in Derived. But can we do the same for a public constructor of Base class?

I tried it as follows,

#include <iostream>

using namespace std;

class base
{
      public:
             base(){}
             void print(){ puts("In print"); }
};

class derived : private base
{
      public:
             base::print;
             base::base;   /* Throws an error - Declaration doesnt declare anything*/
             void display(){ puts("In display"); }
};

int main()
{
    derived dObj;
}

It throws an error "Declaration doesnt declare anything" Is what I am trying valid?

Upvotes: 2

Views: 755

Answers (1)

user2k5
user2k5

Reputation: 827

you can use the using syntax. But it does not make much sense of using the base class constructor. I am guessing you want to initialize your base class, right? You can do it like:

#include <iostream>

using namespace std;

class base
{
      public:
             base(){}
             void print(){ puts("In print"); }
};

class derived : private base
{
      public:
             using base::print;
             derived() : base() {} // initialize base class
             void display(){ puts("In display"); }
};

int main()
{
    derived dObj;
}

Upvotes: 2

Related Questions