3

Is there anyway to do a type of "stacking inheritance" where you replace potentially multiple functions of a base class based on other calls?

for example something like:

class Base {
      void func1(){/* do something */}
      void func2(){/* do something */}
};
class A1 {
      void func1(){/* do something else */}
};
class A2 {
      void func2(){/* do something else */}
};

int main(){
   A1 a1obj = new A1();
   A2 a2obj = new A2();
   Base obj = new Base();

   obj = &a1obj;
   obj = &a2obj;
   obj.func1(); //now A1::func1()
   obj.func2(); //now A2::func2()
}

Thank you

  • Open your C++ book to the chapter that explains how to use `std::function`, and read it. – Sam Varshavchik Aug 29 '17 at 12:54
  • Yes, but your functions need to be virtual, you need to derive from the base class, and you'll need to use pointers or references if you're using the base type for polymorphism to work. – Luchian Grigore Aug 29 '17 at 12:54
  • This will probably be answered [by reading a couple of good beginners books](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Some programmer dude Aug 29 '17 at 12:54

1 Answers1

2

There are virtual functions and multiple inheritance (which should be avoided if possible) in C++.

What you could do in this case is:

class Base {
      virtual void func1(){/* do something */}
      virtual void func2(){/* do something */}
};
class A1: public Base {
      void func1() override {/* do something else */}
};
class A2: public A1 {
      void func2() override {/* do something else */}
};

int main(){
   A2 a2obj;
   Base* obj = &a2obj;

   obj->func1(); //now A1::func1()
   obj->func2(); //now A2::func2()
}

you could even skip instantiating the Base object and just do

int main(){
   A2 obj;

   obj.func1(); //now A1::func1()
   obj.func2(); //now A2::func2()
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
George Hanna
  • 382
  • 2
  • 15