user7431005
user7431005

Reputation: 4539

unique pointer of base class with derived member

For my C++ program I have a lot of classes where a member should be of one of two types which have the same base class.

I thought I could implement this with pointers but I don't get it to work.

Example: lets assume we have a class A with a member b_ of class B:

class A{
public:
    A(B b): b_{b} {}
private:
    B b_;
}

The class B has only one function which is pure virtual:

class B{
public:
    virtual void print() = 0;
}

now I have two derived classes of B and I want to change A in a way, that it could hold eihther objects of class B1 or B2:

class B1: public B{
public:
    void print(){cout << "B1\n";}
}    

class B2: public B{
public:
    void print(){cout << "B2\n";}
}

My plan was to use unique pointers:

class A{
public:
    A(std::unique_ptr<B> b): b_{std::move(b)} {}
private:
    std::unique_ptr<B> b_;
}

int main(){

std::unique_ptr<B> b;
if (some condition){
    b = make_unique<B1>(new B1()) ///?
}else{
    b = make_unique<B2>(new B2()) ///?
}
A(b);
A.getB()->print();
}

Upvotes: 1

Views: 1694

Answers (1)

dani
dani

Reputation: 3887

There are several mistakes on your code. First of, you can't have two definitions of A. Second, you must pass the unique_ptr as r-value reference (std::move) since it is not copyable. Last, make a variable of type A (a) and then call methods on it.

#include <memory>
#include <iostream>

using namespace std;

class B{
public:
    virtual void print() = 0;
    virtual ~B() {};
};

class B1: public B{
public:
    void print(){cout << "B1\n";}
};

class B2: public B{
public:
    void print(){cout << "B2\n";}
};

class A{
public:
    A(std::unique_ptr<B> b): b_{std::move(b)} {}
    auto *getB() { return b_.get(); }
private:
    std::unique_ptr<B> b_;
};

int main()
{
    std::unique_ptr<B> b;
    if(false)
        b = make_unique<B1>();
    else
        b = make_unique<B2>();

    A a(std::move(b));
    a.getB()->print();
}

Upvotes: 2

Related Questions