Hi all,

class A
{
   public:
           A();
           ~A();
}

class B
{
    public:
          B();
          ~B();
    private:
      A *a; ->declares a pointer to class A object
      A a; -> holds the class A object

}

Whats the difference between the 2 type of declaration of a class A instance? Are there any rules as to when to use pointer and when to use just object?

Please advise.

Cheers!

Edited 3 Years Ago by Dani: Formatting fixed

Pointers are often used in combination with dynamic memory allocation ...
Lets say you want to create a table of objects, but it depends on the situation where the program is in, you would rather use a pointer to a table of objects (dynamic memory allocation) ...
But when you're always having/needing the same number of objects you can better use the normal declaration ...

Hope this helps !

Thanks for the prompt reply.

Is the usage link with any OOD concepts or is it purely the memory allocation difference?

In a situation when you need to allocate another object for some task you can use the pointers of that class to fulfill the requirement.
lets just say,
i require to create another object of class_name * p;
so it will be like:

if(condition.....)
p = new data_type;

it will create the new allocated object of that class which you can use further.

Hummed I guess you meant something like:

class_name *p;

if (condition)
{
    p = new class_name;
}

Edited 4 Years Ago by neithan

This article has been dead for over six months. Start a new discussion instead.