Re: I need help with "Inheritance" and "Polymorphism"
On Sun, 30 Apr 2006 19:46:30 -0700, Fao wrote:
The only problem I have now is that I have to enter the data twice to
get the program to run correctly
shouldn't the "input( )" from "SumType" be pulled to other functions
due to the inheritance? I tried a few a
No - inheritance is a relationship between _classes_, but objects of
these classes remain separate. Just as if you create two ints, they
have separate values, and when you create two SumType objects, they will
each have a separate list of numbers, when you you create a SumType object
and a MaxType object, they will each have separate members.
A class is kind of like a blueprint or specification, it says what members
will exist in any object of that class (that is, any object built to that
specification). But it does not itself have any members (just like a
blueprint for a house does not have actual walls), and the members of all
the objects of that class are separate (just as two houses built from the
same blueprint will have separate walls). This is a pretty basic
distinction which is really vital for understanding object-oriented
programming, so you might want to reread the relevant sections in your
textbook or notes until you're sure you understand it.
So, you can't have one object do the input, because then the numbers
won't be available to the other objects. What you should do is separate
the input from the calculation. For instance:
class Calculator
{
public:
std::vector<int> numbers_;
// The constructor makes a copy of a
// vector of numbers passed to it.
Calculator(const std::vector<int>& numbers)
: numbers_(numbers)
{ }
virtual int calculate();
// Note that there's no input function here.
// Instead, make input a non-member function and call it
// before you create objects of any of the Calculator
// subclasses
};
// The base class calculate function doesn't perform a
// calculation but prints an error message. It doesn't
// really make sense to provide an implementation
// for the function here. To find out the best practice in this case,
// look up "pure virtual functions"
int Calculator::calculate()
{
std::cerr << "Warning! No calculation performed\n";
return 0;
}
class SumCalculator : public Calculator
{
public:
virtual int calculate();
};
int SumCalculator::calculate()
{
// You can put your implementation of the
// sum calculation here.
}
Then, in your main function, first input the numbers, then pass the
numbers to the constructor when you create each object that will do the
different sort of calculations.
int main()
{
std::vector<int> numbers;
input(numbers);
SumCalculator sum(numbers);
std::cout << "Sum: " << sum.calculate() << std::endl;
}