Search code examples
c++pointersinheritanceshared-ptrabstract-base-class

Return Base class shared pointer using derived class C++


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.


Solution

  • This should do:

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