简体   繁体   中英

How can i return an object pointed to by an abstract class pointer?

So to summarize I have something equivalent to

class A{
public:
    virtual void foo() const = 0;
};

class B : public A{
public:
    B(){};
    void foo() const override{
        //some code
    };
};

class C{
public:
    C(){};
    B someFunction();
private:
    A* x;
};

and A* x; points to some B object and I need someFuntion() to return that object that x is pointing to. I've tried just doing return *x but that doesn't work.

You must down-cast the x into B before de-reference.

class C
{
public:
   C() {};
   B someFunction()
   {
      return *static_cast<B*>(x); // like this
   }
private:
   A* x = new B;
};

You need also provide the virtual ~A() , not to have undefined behavior. When to use virtual destructors?

class A 
{
public:
   virtual void foo() const = 0;
   virtual ~A() = default;
};

If you know that x points to a B object then cast it first.

return *static_cast<B*>(x);

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