Feedback I got was that I had one or more memory leaks. So I wonder if I have understood this correctly.
Here is some code, all flavors have the same code only the names are different, flavours are BlackCurrant, Strawberry and Wine.
#ifndef BOTTLE_H
#define BOTTLE_H
#include <string>
// Has no .cpp file!
class Bottle
{
public:
virtual std::string getLiquid() = 0;
};
#endif
#ifndef WINE_H
#define WINE_H
#include "bottle.h"
class Wine : public Bottle
{
public:
Wine(Bottle *bottle, int count);
virtual std::string getLiquid();
private:
std::string m_Liquid;
Bottle *m_Bottle;
};
#endif
#ifndef WATER_H
#define WATER_H
#include "bottle.h"
class Water : public Bottle
{
public:
Water();
virtual std::string getLiquid();
private:
std::string m_Liquid;
};
#endif
#include "wine.h"
Wine::~Wine()
{
}
Wine::Wine(Bottle *bottle, int count)
{
m_Bottle = bottle;
if(count > 0)
m_Liquid = ", white wine";
else
m_Liquid = " White wine";
}
std::string Wine::getLiquid()
{
return m_Bottle->getLiquid() + m_Liquid;
}
#include "bottle.h"
#include "water.h"
#include "strawberry.h"
#include "blackcurrant.h"
#include "wine.h"
#include <iostream>
using namespace std;
int main()
{
Bottle *bottle;
bottle = new Water;
int x = 0, count = 0;
while(x != 5)
{
cout << "Choose your flavor:\n1.Strawberry\n2.Blackcurrant\n3.Plain\n4. Wine\nOption: ";
cin >> x;
switch(x)
{
case 1:
bottle = new Strawberry(bottle, count);
cout << bottle->getLiquid() + "!\n\n";
count++;
break;
case 2:
bottle = new Blackcurrant(bottle, count);
cout << bottle->getLiquid() + "!\n\n";
count++;
break;
case 3:
delete bottle; // To "clear" it.
count = 0;
bottle = new Water;
cout << bottle->getLiquid() + "has no flavour!\n";
break;
case 4:
bottle = new Wine(bottle, count);
cout << bottle->getLiquid() + "!\n\n";
count++;
break;
default:
cout << "I do not think you wanna drink this!\n\n";
break;
}
}
//bottle = new Water;
delete bottle; // I added this since I only use "new" in this part of the code.
cin.ignore();
cin.get();
return 0;
}
Do I use delete correctly here? Or have I forgot it somewhere?
I think I have fixed it but I can't be sure, so would anyone be kind enough to help me?
I might have forgot something, I didn't wanna flood you with code that was identical but if something is
unclear I can add the rest of the code.

New Topic/Question
Reply




MultiQuote







|