jeudi 20 septembre 2018

How to call member function specific to derived class using base class interface pointer in c++?

I have below code,

File: Interface.h
class Interface {
  public:
  virtual void method1() = 0;
};


File: Intermediate.h
class Intermediate : public Interface {
};


File: A.h
class A : public Intermediate {
  public:
  void methodSpecificToA() {
    cout << "methodSpecificToA in class A";
  }
  void method1() {
    cout << "implemented method1 in class A";
  }
};

File: B.h
class B : public Intermediate {
  public:
  void methdo1() {
    cout << "method1 is called in class B";
  }
};

int main() {
  Interface* i_ptr = new A();
  i_ptr->method1();
  return 0;
}

My requirement is, I want to call function methodSpecificToA() using i_ptr. But I can't do that as methodSpecificToA is not pure virtual or not defined in Interface class.

So how can I do this without writing default 'methodSpecificToA()' in Interface class?

If I make 'methodSpecificToA()' is as pure virtual, then class B is forced to implement 'methodSpecificToA()' which is not expected.

What would be the best approach?

Aucun commentaire:

Enregistrer un commentaire