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;

Oh, thanks!

I feel stupid :P

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

Ok no worries then ;), keep experimenting!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.