Pointer or Object

Hello everyone, I am a newbie at C++ programming and have been studying it through tutorials through over the Internet. So far I've been able to write some simple programs but most of the time it's trial and error. I've never understood the difference between

1
2
3
4
5
6
7
8
9
10
11
class Someclass()
{
   public:
      void function1() {...}
      int function2() {...}
};

int main(int *argc, char **argv)
{
   Someclass obj; obj.function1();
}


and

1
2
3
4
5
6
7
8
9
10
11
class Someclass()
{
   public:
      void function1() {...}
      int function2() {...}
};

int main(int *argc, char **argv)
{
   Someclass *obj = new Someclass; obj->function1();
}


Thank you in advance for the replies.
Last edited on
A pointer is an object. We go through this "what is a pointer" so often here that there are permanent articles about it. Please read them first.

Here, read this: http://www.cplusplus.com/articles/EN3hAqkS/

and this: http://www.cplusplus.com/articles/z186b7Xj/

If you still don't understand what a pointer is, come back and ask more.
Last edited on
closed account (1vRz3TCk)
a.b
Structure reference operator ("member b of object a")

a->b
Structure dereference operator ("member b of object pointed to by a")

-----------------//-----------------
edit:

Someclass obj; //here obj is an abject of type Someclass

Someclass *obj = new Someclass; // here obj is a pointer to an object of type Someclass
Last edited on
Not completely sure about this but i think that when you say
Someclass obj;
it pushes the obj in the stack and does stuff with it.

and with
Someclass *obj = new Someclass;
it allocates memory in the heap, which is a bigger place than stack, and puts the obj there. If I'm right I guess you should use new alot to avoid stack overflows.

also with new you have to delete it.
Someclass *obj = new Someclass; it allocates memory in the heap, which is a bigger place than stack, and puts the obj there.


It does; note that you get two objects. One pointer (on the stack) for actually accessing the object on the heap, and one Someclass (on the heap). Not realising that a pointer is a complete object in its own right is a common beginner error and one that causes no end of confusion in people's code, so I thought it worth reiterating.
Topic archived. No new replies allowed.