chk this piece of code

#include<iostream.h>
using namespace std;

class hi
{
public:
void print()
{
cout<<"hi";
}
}obj;

int main()
{
hi *h;
h->print();
}

output---> hi

--------------------------------------------------------

#include<iostream.h>
using namespace std;

class hi
{
public:
void print()
{
cout<<"hi";
}
}obj;

int main()
{
obj.print();
}

output---> hi
--------------------------------------------------------------------------

My Question is what actually makes the first one [( ie) use of pointers in classes] advantageous rather the second one ??

atleast explain me when this case is more advantageous rather than the second one inspite of same output

My question may look lame but i need some help ..

please ..

thanks

>>what actually makes the first one [( ie) use of pointers in classes] advantageous rather the second one ??

Nothing. The two examples you posted the first one (ignoring the error in the code) is actually less advantagous, not more advantagous because the pointer is unnecessary because there is a global object that should be used.

Pointer to class becomes useful when you get into data structures.

chk this piece of code

#include<iostream.h>
using namespace std;

class hi
{
public:
void print()
{
cout<<"hi";
}
}obj;

int main()
{
hi *h;
h->print();
}

output---> hi

This method has the "advantage" of crashing the whole program because you're trying to use an uninitialised pointer.

I dont know y this would crash ... it worked fine with my compiler ..

I dont know y this would crash ... it worked fine with my compiler ..

You might have just gotten lucky one time, but these things are neither predictable, nor pleasant.

With using an uninitialised pointer variable, any half-decent compiler should issue a C4700 (not an error, but a warning). And you should get an access violation with that statement where you're calling a method on the uninitialised pointer variable. Just run it under the debugger.

This is an extremely basic thing, so I won't go further explaining. Just read up on uninitialised pointers and the error modes associated with them, and what they could do to your program.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.