-2
class A 
{
public:
    virtual void show()
    {
        cout << "you are in A";
    }
};

class B : public A
{
public:
    void show()
    {
        cout << "you are in B";
    }
};

int main()
{
    A *a[5];
    A **aa[5];
    B *b[5];

    for (int i = 0; i < 5; i++)
    {
        a[i] = new A;
        aa[i] = &a[i];
        aa[i]->show();
        b[i] = new B;
        aa[i] = &b[i];
        aa[i]->show();
    }

    return 0;
}

error : request for member 'show' in *aa[i] which of type pointer 'A*'

error : invalid conversion from 'B**' to 'A**' [-fpermisive]

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Anmol Singh
  • 43
  • 1
  • 7

1 Answers1

4

Since you have A **aa[5], it is an array of pointers to pointers, so you need triple indirection to call the show method

(*aa[i])->show();

You also can't store B** in it, as you can only (implicitly) convert to a base class with a single level of indirection.

However, it is not at all clear what you are trying to do. More commonly you would just use an array of pointers and only need double indirection:

A *a[5];
for (i = 0; i < 5; ++i)
    if (i & 1)
        a[i] = new A;
    else
        a[i] = new B;
for (i = 0; i < 5; ++i)
    a[i]->show();

double pointers are rarely needed, so why are you using them?

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
  • thanks for your help, but my second error still exist error : invalid conversion from 'B**' to 'A**' [-fpermisive] – Anmol Singh Oct 20 '20 at 02:47
  • Right, because you can't convert to the base class with more than one indirection -- it makes no sense to do so (and is unsafe, in general), so the compiler doesn't let you do it. – Chris Dodd Oct 20 '20 at 02:58
  • i am using virtual function, so how can i call show () of B class from pointer of base class A in case of dynamic memory allocation ? – Anmol Singh Oct 20 '20 at 03:09
  • @AnmolSingh: that's the way virtual functions work -- they call based on the dynamic (actual) type of the object, not the type of the pointer. – Chris Dodd Oct 20 '20 at 19:18