Conversion between classes

architecture, c++

Solution

It entirely depends on how you intend to use it, but in many cases, the cleanest way to do this is to implement a converting constructor:

class B { };
class A
{
    A(const B& b) { }
};

B b;
A a = b; //< calls converting constructor

(of course, you could implement a converting constructor for converting from `A` to `B`, as well)

Problem

Let's say we have a class called A and another one called B. and we want to have a conversion method that converts A to B. In the software architecture point of view, which one is preferred? - write `A.export()` - write `B.import()` - write a converter class, i.e. `convert(A, B)` or `Convert(A)` or ... if the language matters, I'm using C++

Original source