简体   繁体   中英

convert an object created with base class ctor to a derived class

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

实现此目的的唯一方法是创建一个新对象,然后将数据从旧对象移出。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM