Reputation: 31
Hello I have been stuck on trying to figure this out. I am passing an object in this function to compare two different volumes, however I am required to use two different classes (inheritance) in order to receive the information for the volume. When I try to pass the object I am having a hard time trying to use both the circleType and cylinderType classes with the passed object. I am not sure how to work this question properly, but I am trying to figure out how to use two different classes in a comparison function.
bool equalVolume(const circleType&, const cylinderType& ct)
{
if (ct.CalcVolume != Calvolume())
{
return false;
}
else
{
return true;
}
}
Upvotes: 0
Views: 219
Reputation: 780
I'd have thought it might look something like this:
bool equalVolume(const circleType& cir, const cylinderType& cyl)
{
return cir.CalcVolume == cyl.CalcVolume;
}
As another user has pointed out, I'd probably add a volume() getter function and use that instead of directly accessing the CalcVolume (which is probably a data member).
PS: Writing a function to compare volumes like this looks superfluous because you could always just compare the volumes inside an if() condition instead.
Upvotes: 2
Reputation: 41770
There is multiple problems with your implementation. You receive both shapes, but the circleType
has no variant name. Then I see you tried to call the function calcVolume
with no variable. How can you calculate the volume of nothing? Well, you can't. You have to use the name of the circle and refer to it.
// v---- Give a name to your circle
bool equalVolume(const CircleType& myCircle, const CylinderType& myCylinder) {
// v---- Call calcVolume with myCircle
if (myCircle.calcVolume() != myCylinder.calcVolume()) {
// call with the cylinder --^
return false
} else {
return true;
}
}
By the way, since the comparison is already an expression of type bool
, you can shrink your function to that:
bool equalVolume(const CircleType& myCircle, const CylinderType& myCylinder) {
return myCircle.calcVolume() == myCylinder.calcVolume();
}
I would rather create a function that returns the volume and leave the implementation to the user. It would look like that:
using volume_t = double;
struct Circle {
volume_t volume() const {
// return volume here
}
};
struct Cylinder {
volume_t volume() const {
// return volume here
}
};
And then, instead of using the isVolumeEqual
function, just do that:
if (myCircle.volume() == myCylinder.volume()) {
// code here ...
}
If you really want to implement the volume equal function, I would do it like that:
template<typename S1, typename S2>
auto volumeEqual(const S1& s1, const S2& s2) -> decltype(s1.volume() == s2.volume()) {
return s1.volume() == s2.volume();
}
That way, you implement a volumeEqual
for all possible shapes that has the volume()
function.
Upvotes: 2