In: Computer Science
In C++
ifdef QUESTION2
/*
2. Create a header and implementation for a class
named bottle. bottle objects should be able
to set and get their size in ounces, the type of
liquid it contains(as a string), the amount of
liquid it contains and whether they are less than
another bottle object(based on the amount
of liquid they contain). Do not comment your
code.
*/
std::cout << "QUESTION 2: " << std::endl << std::endl;
std::cout << std::boolalpha;
bottle myBottle;
bottle anotherBottle;
myBottle.setLiquidType("water");
myBottle.setSize(32.0);
myBottle.setFillAmount(20.0);
anotherBottle.setLiquidType(myBottle.getLiquidType());
anotherBottle.setSize(myBottle.getSize());
anotherBottle.setFillAmount(10.0);
std::cout << "myBottle is less than anotherBottle: " << myBottle.isLessThan(anotherBottle) << std::endl;
std::cout << std::endl << std::endl;
#endif
Solution:
I have createed 2 files.
Codes:
bottle.h
#ifndef BOTTLE_H
#define BOTTLE_H
#include <iostream>
#include <string>
using namespace std;
class bottle{
private:
string liquidType;
float size;
float fillAmount;
public:
string getLiquidType();
void setLiquidType(string);
float getSize();
void setSize(float);
float getFillAmount();
void setFillAmount(float);
bool isLessThan(bottle );
};
#endif
bottle.cpp
#include "bottle.h"
string bottle::getLiquidType()
{
return liquidType;
}
void bottle::setLiquidType(string liquidType)
{
this->liquidType = liquidType;
}
float bottle::getSize()
{
return size;
}
void bottle::setSize(float size)
{
this->size = size;
}
float bottle::getFillAmount()
{
return fillAmount;
}
void bottle::setFillAmount(float fillAmount)
{
this->fillAmount = fillAmount;
}
bool bottle::isLessThan(bottle obj)
{
return this->fillAmount<obj.fillAmount;
}
Here is the driver code:
Note: I have used the given code in the question
#include <iostream>
#include "bottle.h"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
std::cout << "QUESTION 2: " << std::endl << std::endl;
std::cout << std::boolalpha;
bottle myBottle;
bottle anotherBottle;
myBottle.setLiquidType("water");
myBottle.setSize(32.0);
myBottle.setFillAmount(20.0);
anotherBottle.setLiquidType(myBottle.getLiquidType());
anotherBottle.setSize(myBottle.getSize());
anotherBottle.setFillAmount(10.0);
std::cout << "myBottle is less than anotherBottle: " << myBottle.isLessThan(anotherBottle) << std::endl;
std::cout << std::endl << std::endl;
return 0;
}
Obtained output: