I am unfamiliar with using virtual functions and was wondering how I would implement them correctly. I have a class called 'car' and an abstract class called 'Carbon Footprint' and want to have a one pure virtual function called
getCarbonFootprint(). I am trying to get the 'car' class to inherit this getCarbonFootprint() function. Cheers to anyone that can lend a hand
Not sure why getCarbonFootprint() needs to be virtual (other than perhaps that's your assignment). From your limited description, getCarbonFootprint() could just as easily be a non-virtual member of CarbonFootPrint.
The purpose of virtual functions is to exhibit different behavior in different derived classes. A classic example is a base class of Shape. Square, Circle and Triangle all derive from Shape. Shape has a pure virtual member Area(). Area() has no meaning for the base class, each derived class calculates area differently. Yet, you can call shape->area() and invoke the Area() function for the appropriate derived class.
Since you haven't fully described your assignment, I've made the assumption that the base class has a member m_cfp that's accessible from its derived classes.
class CarbonFootPrint
{
protected:
int m_cfp; // Or whatever you're measuring
public:
CarbonFootPrint (int cfp)
{ m_cfp = cfp;
}
virtual ~CarbonFootPrint ()
{}
virtualint getCarbonFootprint () const = 0;
};
class Car : public CarbonFootPrint
{
public:
Car () : CarbonFootPrint (50) // Assume a car has a CFP of 50
{}
int getCarbonFootprint () const
{ return m_cfp;
}
};
@AbstractionAnon: how'd you explain public inheritance of Car from CarbonFootPrint? What sort of relationship would that entail b/w the two classes? Admittedly private/protected inheritance (as CarbonFootPrint <- Car should be) support virtual functions but the only query on these lines that I found did not really have any good answers as to why virtual functions might be necessary in non-public inheritance with some of the replies sceptical about having virtual functions under such inheritance http://stackoverflow.com/questions/2157854/virtual-function-in-private-or-protected-inheritance