0

I have a an interface:

/*base.hpp */

class Base {
    protected:  
    Base() = default;

    public:
    Base(Base const &) = delete;
    Base &operator=(Base const &) = delete;
    Base(Base &&) = delete;
    Base &operator=(Base &&) = delete;
    virtual ~Base() = default;

    virtual void Function1() = 0;
};

Also there is a function in this interface:

std::shared_ptr<Base> **getBase**();   //this will return the instance of Base class 

Since function in base class is pure virtual, sample Derived class is below:

#inclide "base.hpp"
class Derived : public Base
{
    public:
    Derived();
    ~Derived();            
    virtual void Function1() override;
};

In main.cpp -> there is a call to getBase()

std::shared_ptr<Base> ptr{ nullptr };
void gettheproxy() {    
    ptr = getBase(); //call to get baseclass instance   
}

Implementation of getBase method (in separate file getBase.cpp)

#include "base.hpp"
#include "derived.hpp"

Derived d;
std::shared_ptr<Base> getBase()
{
    std::shared_ptr<Base> *b= &d;
    return b;
}

Error: cannot convert ‘Base*’ to Base’ in initialization

What is the correct way to get base class instance from derived class implementation? Note: I have to follow this design of classes due to code dependency.

Incredible
  • 3,495
  • 8
  • 49
  • 77
  • 2
    `std::shared_ptr b(&derived);` will do but it will try to delete the global static variable at some point, which is UB. – Aykhan Hagverdili Jul 03 '22 at 11:17
  • 1
    You'll get yourself into trouble sharing the ownership of an object between the stack and the shared pointer object. When the last copy of the shared pointer gets destroyed `delete` is called which will almost certainly crash your program. Btw: you cannot turn a pointer to `Derived` into a pointer to `std::shared_ptr` and even if you could you wouldn't be able to convert `std::shared_ptr*` to `std::shared_ptr` implicitly. – fabian Jul 03 '22 at 11:20
  • @fabian Nitpick: the object in this example is not on the stack. It's a global static object. – Aykhan Hagverdili Jul 03 '22 at 11:23

1 Answers1

2

This should do:

std::shared_ptr<Derived> d = std::make_shared<Derived>();

std::shared_ptr<Base> getBase() { return d; }
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93