Problem with dynamic memory and classes

Hi, guys. I have a problem with dynamic memory allocation and classes. I am to implement a class Folder that has methods to create, delete and print names of folders. The problem is that when call my AddFolder function and it allocates memory for a new folder, I don't seem to be able to access the newly created folder. The compiler doesnt show any error, but when I call printName(), my program stops working. Can you guys tell me what I'm doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
  #include <iostream>
using namespace std;
class Folder
{

    public:
    string name;
    Folder()
    {
        ;
    }
    Folder(string n); 
    void AddFolder(Folder* fold);
    void DelFolder(Folder* fold);
    void printName();
    friend string getName();
};

            string getName()
            {
                    string a;
                    cout << "input folder name:";
                    getline(cin, a);
                    return a;
            }


            Folder::Folder(string n)
            {
                name=n;
                cout << "New folder was created.";
            }

            void Folder::AddFolder(Folder* fold)
            {
                fold=new Folder(getName());
                if(fold==NULL) {cout << "o shet";};
            }

            void Folder::DelFolder(Folder* fold)
            {
                delete fold;
                cout << "a folder has been deleted.";
            }

            void Folder::printName()
            {
                cout << name << endl;
            }
            

int main()
{
    Folder k(getName());
    Folder* ptr;
    k.AddFolder(ptr); //creating new folder , seems to be working fine here 
    ptr->printName();//on this line my program stops working

    //(*ptr).printName() also not working

    return 0;
}
You are passing the pointer by value, so the modification doesn't get through to the main program. Try passing the pointer by reference. Also, the NULL check for the folder is completely useless ('new' throws on error rather than returning NULL), and when you have deleted something it is common practice to set the value of the pointer to NULL as well, unless you know its just about to go out of scope or something like that (but of course you don't in a member functions taking the pointer).
what do you mean by 'pass it as reference'? I don't quite understand it. Can you type it please?
 
void Folder::addFolder(Folder*& fold)
ill try it, thanks :). Thing is, my assignement was to fo it with

void Folder::AddFolder(Folder* fold)

without reference.
Topic archived. No new replies allowed.