I have a abstract class named Base
from which I derived a class(Derived
) as follows:
#include <iostream>
#include <string>
#include <memory>
class Base
{
public:
virtual void printClass()const = 0;
virtual ~Base(){}
};
class Derived: public Base
{
private:
int m_var1;
std::string m_var2;
public:
Derived() = default;
Derived(const int& v1, const std::string& v2)
:m_var1(v1), m_var2(v2)
{ }
void printClass()const override
{
std::cout << "Derived Class with\t";
std::cout << m_var1 << " " << m_var2 << std::endl;
}
~Derived(){ std::cout << "Derived destroyed" << std::endl; }
};
Now in the main()
to make use of polymorphisum I could declare as follows:
int main()
{
std::shared_ptr<Base> Obj[3];
Obj[0] = std::make_shared<Derived>(1,"One");
Obj[1] = std::make_shared<Derived>(2,"Two");
Obj[2] = std::make_shared<Derived>(3,"Three");
for(const auto& it: Obj)
it->printClass();
return 0;
}
However, I am currently trying to learn more about the std::shared_ptr<>()
and its custom deletion technics and I came across following statement.
std::shared_ptr<Base> Obj(new Derived[3], [](Derived* obj){ delete[] obj; });
and
std::shared_ptr<Base> Obj(new Derived[3] = {
{1,"One"},
{2,"Two"},
{3,"Three"}
},
[](Derived* obj){ delete[] obj; });
My questions are:
- Why I can not initialize or pass values to the constructor of
Derived
class in following manner, even-though I have a costume defined constructor available for thederived
class? or am I missing something? - If so what would be the correct way of initializing and accessing
such array of
derived class
elements?