Hello everyone!

I wrote a basic c++ program using classes and pointers. Although it compiles without any errors, it will not run, saying "This program has stopped working". I am assuming that this issue may have been created by a memory leak, but I made sure to delete all dynamically allocated variables in the class deconstructor. Any help would be greatly appreciated!

#include <iostream>
using namespace std;

class Book
{
    public:
        Book();
        ~Book() {delete hasSetPages; delete hasSetColor;};
        void setPages(int x);
        int getPages();
        void setColor(string x);
        string getColor();
        bool *hasSetPages;
        bool *hasSetColor;
        int pages;
        string color;
};

Book::Book()
{
    *hasSetPages = new bool;
    *hasSetColor = new bool;
    *hasSetPages = false;
    *hasSetColor = false;
    pages = 0;
};

void Book::setPages(int x)
{
    if(*hasSetPages == false)
    {
        pages = x;
    }
    if(*hasSetPages == true)
    {
        cout << "You already set the pages!";
    }
};

int Book::getPages()
{
    return pages;
};

void Book::setColor(string x)
{
    if(*hasSetColor == false)
    {
        color = x;
    }
    if(*hasSetColor == true)
    {
        cout << "You already set the color!";
    }
};

string Book::getColor()
{
    return color;
};

int main()
{
    Book a;
    cout << *(a.hasSetPages);
    a.setPages(110);
    a.setColor("Brown");
    cout << *(a.hasSetPages);
    cout << a.getPages();
    cout << endl;
    cout << a.getColor();
    cout << endl;
    a.setPages(200);
    return 0;
}

Lines 21 and 22 are wrong. They should be

hasSetPages = new bool;
hasSetColor = new bool;

Edited 6 Years Ago by NathanOliver: n/a

Can I ask why you want to use dynamic memory allocation in this case? Rather than just using 'bool hasSetPages;' and forget about new/delete;

I wanted to see the result of trying to use pointers with classes, there was really not much of a reason :P

This question has already been answered. Start a new discussion instead.