doubt about class pointers...

hi,,
i'm new to the forum.i have been coding in c++ for about a year since i first learnt it on this site.i've started coding games recently and i have some general doubts which probably should be in the beginner section but here goes anyway...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//in something.cpp
class something
{
   some members;
   ..
   ..
}

//in main.cpp
something *s;
s=new something;
//
 ...other code...
// 

I've always used pointers to refer to classes and their members and this has worked well for me...but will there be any difference if i directly declare the object like so...?
1
2
3
4
5
6
7
//in main.cpp

something s;

//
 ...other code...
// 

i've used pointers without understanding the pros and cons so i would appreciate it if someone shed some light on this...will using pointers make it slower faster or make no difference at all...?the only difference i can make out is that i dont need to manually call the destuctors if i declare the object directly...
If you are using only basic classes ( ie not polymorphism or other things ) it's better if you use objects directly instead of using pointer as it is simpler and you don't risk memory leaks.
closed account (S6k9GNh0)
Say you have a nice pair class:
1
2
3
4
5
6
template <class T>
class Pair
{
public:
   T x;
   T y;

This is nice and relatively small. Only 32 (?) bytes are being used here. This can be initialized on stack and should work just fine with no problems. But if you have something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
class BigAssClass
{
public:
   long getId();
   std::string getName();
   void * getLocation();
   
private:
   long id;
   std::string name;
   std::pair location;
   int &list; 
}


Then you'd probably want to dynamically allocate this class and create a beautiful pointer to it.
Pointers should be used when any of the following conditions are true:
1) The object is too large to put on the stack;
2) You need the object to live beyond the scope in which it is declared;
3) You need polymorphism

Topic archived. No new replies allowed.