lostsky25
lostsky25

Reputation: 95

Unique pointer to Base class

I have two classes, Base which contains virtual method and D which contains overload that method. I want to create a variable with Base type, than pass there class D which inherits class Base. It's my implementation:

#include <iostream>
#include <vector>
#include <memory>
#include <cstdio>
#include <fstream>
#include <cassert>
#include <functional>


class Base {
public:
  virtual void bar() { std::cout << "B::bar\n"; }
  //virtual ~Base() = default;
};

typedef Base* Maker();
Maker* arr[10];

class D : Base
{
public:
    D() { std::cout << "D::D\n";  }
    ~D() { std::cout << "D::~D\n";  }
    void bar() override { std::cout << "D::bar\n";  }
};

template <class T>
Base* make(){
    return new T;
}

int main()
{
  std::unique_ptr<Base> p1(new D);
  p1->bar();

  //arr[0] = make<D>();

  return 0;
}

Btw, it's working with structs, but when I try to implement that though classes I'll get error.

Upvotes: 1

Views: 2337

Answers (2)

Sam Varshavchik
Sam Varshavchik

Reputation: 118415

The compilation error has two reasons, and both must be fixed.

class D : Base

Base is privately inherited, so only members of D can convert a pointer to D to a pointer to B, you must inherit publicly:

class D : public Base

Second problem is here:

typedef Base* Maker();

Maker* arr[10];

// ...

arr[0] = make<D>();

arr is an array of function pointers. "Make()" is an expression that evaluates to a function call that returns a Base *. Assigning a Base * to some function pointer doesn't make any sense, whatsoever. You meant:

arr[0] = &make<D>;

With both fixes, the shown code compiles.

Upvotes: 1

Igor Tandetnik
Igor Tandetnik

Reputation: 52571

D inherits from B privately. Therefore, D* is not convertible to B*. You likely want class D : public Base { ... };

Upvotes: 4

Related Questions