PDA

View Full Version : *obj vs obj



marf
5th July 2008, 03:55
I'd like to think of myself as a intermediate programmer but I think I have a somewhat newb question.

I'm making a class, so I'm making the appropriate class1.h and class1.cpp

in the class1.h I have something like so

Method 1

/*Header File*/
...
private:
QHttp _http;
...


then within my class1.cpp I use it in methods like


/*Cpp File*/
...
_http.setHost("http://www.mysite.com");

connect( &_http, SIGNAL( done( bool ) ), this, SLOT( handleDone( bool ) ) );
...


which works just fine. But I can also change the two above to the following

Method 2

/*Header File*/
...
private:
QHttp *_http;
...

and again

/*Cpp File*/
...
_http = new QHttp("http://www.mysite.com");
_http -> setHost("http://www.myothersite.com");
connect( _http, SIGNAL( done( bool ) ), this, SLOT( handleDone( bool ) ) );
...


I know what I'm doing here, the first method is creating a QHttp variable, and what I assume is using the default constructor with null parameters. I then can use the methods of the class by using a period <.> with the method name. I can also connect the signal by using the & symbol (passing by reference).

If I use method 2, I am just creating a pointer to a QHttp, not calling the constructor, which is why I need to actually call the default constructor in the code. Then to call the methods I have to use -> instead. And when connecting the signal no need to use the &.

so my questions

Both methods work, which one is better and for what situations?

JimDaniel
5th July 2008, 05:08
With the first method, QHttp _http, you are creating the object on the stack, and it will be there as long as the class is around. For objects of significant size that can be very inefficient, memory-wise, as stack memory is limited.

But luckily there is more abundant heap memory you can use, and C++ has pointers, which are variables that point to objects created on the heap.

So normally for objects of significant size, if you need them to have class scope, you create the object on the heap with "new," and store a pointer variable to that object in the class, instead of storing the object itself, because its more efficient. Consider this code:



QHttp * p_http = new QHttp();
QHttp http;

cout << sizeof(p_http) << endl;
cout << sizeof(http) << endl;



Output:
4
8

Not a huge difference in this situation, but GUI objects are a much different story. For example:



QWidget * p_widget = new QWidget();
QWidget widget;

cout << sizeof(p_widget) << endl;
cout << sizeof(widget) << endl;



Output:
4
20

Something to keep in mind, a pointer variable is not the object. It is only a variable that stores the memory address of an object - about the size of an int. When you use the -> (called the dereference arrow) on the pointer, you are essentially saying "give me the object you are pointing to." That is why you can then use the methods contained in the object.

Hope that helps...