0

If have a class:

class classA {
public:
    int z = 5;
};

I understand RAII to be when I write classA Aobject but what do I do if I want to declare a global pointer?

classA *Aobject;
int main()
{
    Aobject = new classA; //not RAII

    cout << Aobject->z << endl;

    return 1;
}
  • 1
    What do you mean by forward declaring an object? In your example, you are declaring a global pointer. – juanchopanza Dec 08 '12 at 17:19
  • I thought forward declaring was the terminology here, I must be wrong –  Dec 08 '12 at 17:21
  • 1
    It is not the right terminology, but mainly because you are declaring a pointer (unless you consider a pointer to be an object). – juanchopanza Dec 08 '12 at 18:07

1 Answers1

4

I assume that what you mean is you want to declare an object, but you don't want to initialize it right away, perhaps because you don't have all the parameters you need in order to construct it properly yet. Is that correct? Use a smart pointer.

#include <memory>
#include <iostream>

std::unique_ptr<classA> Aobject;
int main()
{
    Aobject.reset(new classA);

    cout << Aobject->z << endl;

    return 1;
}
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274