Suppose I have a type hierarchy:
struct B { ... };
struct D1 : B { ... };
struct D2 : B { ... };
...
struct Dn : B { ... };
Each Di has its own operator==
defined:
struct Di : B
{
bool operator==(const Di&) const { ... }
...
};
I now want to define the B operator==
such that:
struct B
{
bool operator==(const B& that) const
{
// psuedo-code
let i, such the dynamic type of this is Di
let j, such the dynamic type of that is Dj
if (i != j)
return false;
else
return Di::operator==(this, that);
}
}
What is the best way to organize this or write this?
(The end goal is that I want to use the standard container types with a value type of B* (eg std::set<B*>
), but for it to use the custom Di::operator==s
when they are from the same derived class)
The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class.
A base class is an existing class from which the other classes are derived and inherit the methods and properties. A derived class is a class that is constructed from a base class or an existing class. 2. Base class can't acquire the methods and properties of the derived class.
A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class.
A base class is also called parent class or superclass. Derived Class: A class that is created from an existing class. The derived class inherits all members and member functions of a base class. The derived class can have more functionality with respect to the Base class and can easily access the Base class.
Define a protected virtual function in the base class. Make it pure virtual to ensure that each subclass Di
provides an implementation. The function will know the target of the cast, because it belongs to a Di
. Call that function from the operator ==
in the base class, and let it perform the comparison, like this:
struct B {
bool operator==(const B& that) const {
return this->equals(that);
}
protected:
virtual bool equals(const B& other) const=0;
};
struct D1 {
protected:
virtual bool equals(const B& other) const {
D1 *that = dynamic_cast<D1*>(&other);
if (!that) return false;
// Perform D1-specific comparison here.
// You can use the == operator of D1, but you do not have to:
return (*this) == (*that);
}
};
The effect of this construct is making the implementation of the ==
operator virtual.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With