0

I have the following classes:

class Base {
public:
  virtual ~Base(){}
  Base() {}

  virtual void foo() = 0;
};

class Derived : public Base {
public:
  virtual ~Derived(){}
  Derived() : Base() {}

  void foo() { printf("derived : foo\n"); }
};

class IInterface {
public:
  virtual ~IInterface() {}

  virtual void bar() = 0;
};

class C : public Derived, public IInterface {
public:
  virtual ~C(){}
  C() : Derived(){}

  void bar() { printf("C : bar\n"); }
};

now I have a bunch of Derived* objects and I want to apply different interfaces on them :

  Derived* d = new Derived();
  C* c = dynamic_cast<C*>(d);
  c->bar();
  c->foo();

dynamic_cast returns nullptr and with c-style cast i get seg fault. is there anyway to achieve this?

note that my objects are already created with Derived ctor. i just want to treat them differently using Interfaces

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
arash kordi
  • 2,470
  • 1
  • 22
  • 24
  • _"is there anyway to achieve this?"_ No, you can't magically change an objects type once it was constructed. Also see: [What is object slicing?](http://stackoverflow.com/questions/274626/what-is-object-slicing) – πάντα ῥεῖ May 13 '17 at 08:57
  • Looks like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – molbdnilo May 13 '17 at 09:13

2 Answers2

1

The only way to achive this is to create a new object and move the data over from the old object.

doron
  • 27,972
  • 12
  • 65
  • 103
0

Try encapsulating the behaviour that needs to change at runtime. Instead of inheriting from the IInterface, you have a member variable that is an IInterface pointer. Then instead of overriding bar in the child class, you pass the call to bar through to whatever is being pointed at. This allows modular behavior that looks just like polymorphism, but is more flexible:

class IInterface {
public:
  virtual ~IInterface() {}

  virtual void bar() = 0;
};
class Derived : public Base {
public:
  IInterface* m_bar;

  virtual ~Derived(){}
  Derived() : Base(){}

  void bar() {return m_bar->bar(); }
  void foo() { printf("derived : foo\n"); }
};

You then derive and create IInterface objects and can associate any of them with Derived objects.

Jason Lang
  • 1,079
  • 9
  • 17