1

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.

FNParraga
  • 11
  • 1
  • May I ask why you return a value of type `B` instead of `B*` or `B&`? Like this, it will be a copy. – Aziuth Jul 11 '20 at 11:10

2 Answers2

2

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;
};
Const
  • 1,306
  • 1
  • 10
  • 26
1

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

return *static_cast<B*>(x);
john
  • 85,011
  • 4
  • 57
  • 81