Home > Software engineering >  Factory Design and Inheritance
Factory Design and Inheritance

Time:12-16

I'm making a project for my college in which I am implementing factory design but the problem is i cant return the address of object it gives an error conversion "C conversion to inaccessible base class is not allowed".

#include<iostream>

using namespace std;

class card
{
    protected:
       int fee;
       int limit;

    public:
       virtual void setvar() = 0;
};

class silver : card
{
    void setvar()
     {
        fee = 500;
        limit = 10000;
     }
};

class gold : card
{
    void setvar()
      {
         fee = 1000;
         limit = 20000;
      }
};

class platinum : card
{
    void setvar()
     {
        fee = 2000;
        limit = 40000;
     }
};

Error is given here on the return lines of this class FactoryDesign.

class factorydesign
{
    private :
        factorydesign();
    public:
        static card* getcard(int c)
         {
             if (c == 0)
              {
                return new silver();
              }
             else if (c == 1)
              {
                return new gold();
              }
             else if (c == 2)
              {
                return new platinum();
              }
         }

 };
 int main()
 {
      int choice;

      cout << "0 : Silver card\n1 : Golden Card\n2 : Platinum card \n";
      cin >> choice;

      card* obj;
      obj = factorydesign::getcard(choice);

      return 0;
 }

Can anybody please also give a detailed explanation of why it is happening because?

CodePudding user response:

You need to publicly inherit it (with class it default to private)

class silver : public card
{
  //...
};

you cannot access private base outside because, well, it's private (like private member)

CodePudding user response:

Ignoring all of the irrelevant code in the question, the problem is this:

class base {};
class derived : base {};

base *ptr = new derived;

derived inherits privately from base, so, as the error message says, converting that derived* created by new derived to a base* is not legal. The fix is simply to publicly inherit:

class derived : public base {};
  • Related