Saturday, 31 August 2013

Data abstraction and binary methods in C++

Data abstraction and binary methods in C++

I'm new to C++, and am struggling with understanding data abstraction in
combination with binary methods such as equality. I'd like to define an
interface
class A {
public:
static A* Make(int);
virtual ~A() {};
virtual bool Eq(A*) = 0;
};
Using a factory pattern, I can hide the implementation:
class B : public A {
public:
B(int x) : x_(x) {}
bool Eq(A* a) {
return x_ == dynamic_cast<B*>(a)->x_;
}
private:
int x_;
};
A* A::Make(int x) {
return new B(x);
}
I can then use the abstraction:
A* a = A::Make(1);
A* b = A::Make(2);
if (a->Eq(b)) {
cout << "Yes!" << endl;
} else {
cout << "No!" << endl;
}
However, the dynamic cast sucks for a variety of reasons. The biggest
problem as I see it is that one can subclass A with C, and then pass an
object of type C to a->Eq, which would result in undefined behavior. I can
not figure out how to define a binary method such that the code has access
to the private members of both objects. My intuition is that this can be
done using a visitor pattern, but I wasn't able to come up with a
solution.
For those who know ML, I essentially want to do the following:
module A : sig
type t
val make: int -> t
val eq: t -> t -> bool
end = struct
type t = int
let make x = x
let eq x y = (x = y)
end

No comments:

Post a Comment