My aim is to be able to create an object with a different kind of member object of from same class family; in Java
it seems like this:
public class Interface {
public void test();
}
public class MyImpl1 implements Interface {
@Override
public void test() {System.out.println("I am impl 1");}
}
public class MyImpl2 implements Interface {
@Override
public void test() {System.out.println("I am impl 2");}
}
public class A {
public A(Interface myinter) {
_myinter = myinter;
}
Interface _myinter;
}
So that I can create an object with different implementation:
A a(new MyImpl1());
or
A a(new MyImpl2());
(Sorry if there is syntax error in this botched code, it is just to explain what I want)
So, in C++ I think I would implement this with smart pointer to benefit from RAII. Thus, I wrote this code:
#include <iostream>
#include <memory>
using namespace std;
struct Interf {
virtual void test() {cout << "I am Interf" << endl;}
};
struct A {
A(std::unique_ptr<Interf> e) : _e(std::move(e)) {}
std::unique_ptr<Interf> _e;
void test() {_e->test();}
};
struct Impl : public Interf {
void test() {cout << "I am Impl;" << endl;}
};
int main()
{
std::unique_ptr<Interf> b(new Impl);
A a(std::move(b));
a.test();
cout << "fine!" << endl;
return 0;
}
It seems to me working. But, is this a correct way to implement it, or there are errores, or better practices?
Also, in this code, I am not sure if I needed to use
std::move
twice. Is this the correct way to passunique_ptr
to constructor?Another thing I did not understand is why this code does not compile if I remove
_e(std::move(e))
from memberwise init list and put inside the constructor; some one please could also explain what is going on here?
.
struct A {
A(std::unique_ptr<Interf> e) {
_e(std::move(e));
}
...
};