Question

I had 4 classes:

  • List
  • Base
  • A
  • B

I needed to add a class which extends the work of the classes A and B - L3. Classes NewA and NewB implement the function declared in L3.

class Base
{
     virtual void foo() = 0;
}

class A: virtual public Base
{
     void foo();
}
class B: virtual public Base
{
     void foo();
}

class L3: virtual public Base
{
     virtual void bar() = 0;
}
class NewA: public A, virtual public L3
{
     void bar();
}

class NewB: public B, virtual public L3
{
     void bar();
}

How can I call function bar() inside List?

UPD

First List contains objects A and B, but now there NewA and NewB

class List
{
    public:
        void append(Base *sh);
        void next();
        void setBegin();
        Base* curr();
        void out(std::ofstream &ofst);

    protected:
        std::list <Base*> container;
        std::list <Base*>::iterator iter;
}

void List:: next()
{
    iter++;
}

void List:: setBegin()
{
    iter = container.begin();
}

void List:: append(Base* sh)
{
    container.push_back(sh);
}

Base* List::curr()
{
    return *iter;
}

void List::out(ofstream &ofst)
{
    setBegin();
    for (int i=0; i<container.size(); i++)
    {
        cout<<"Out: "<< endl; // I need to call bar() at this line
        next();
    }
}
Was it helpful?

Solution

Base doesn't have method bar(), only L3 (and its derived class) has. So you can't call bar() from Base.

You may do the following:

Base* base = List.curr();
L3* l3 = dynamic_cast<L3*>(base); // l3 is non null if base is non null and IS a L3.

if (l3 != nullptr) {
    // base->bar(); // ILLEGAL
    l3->bar();
}

In the case you know that Base IS a L3 you may use a static_cast:

NewA newA;
Base* base = &newA;
L3* l3 = static_cast<L3*>(base);

newA.bar();
// base->bar(); // ILLEGAL
l3->bar();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top