Public Group

# Static functions or pointers?

This topic is 3029 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi, which example is better?: Ex1:
class A
{
public:
static void doSth() {...}
};

int main()
{
...
A::doSth();
...
}

Ex2:
class A
{
public:
void doSth() {...}
};

int main()
{
...
A* a = new A;
a->doSth();
...
}


##### Share on other sites
Better how?

Also, for the class from Ex 2, you can just write:

int main() {    A a;    a.doSth();}

##### Share on other sites
Neither is "better", they do different things ans should be used appropriately.

##### Share on other sites
Gage64: but your example creates new instance of A, but when for example we have Gui class we have only one Gui ingame so creating new instance of Gui doesn't make any sense.

##### Share on other sites
Which I would choose would depend on what doSth did, exactly. I'd probably go for the second (or, rather, a variant using shared_ptr and weak_ptr as appropriate) since it's not totally inconceivable that you could have more than a single GUI, despite what you say.

##### Share on other sites
"What is better, French toast or the color red?"

That is what your question sounds like. You make it sound as if you have to choose one or the other. But the two aren't really opposites. They aren't even all that closely related.

It sounds like you need to refresh what those terms actually mean.

First, you don't have to use a pointer in C++ to call a non-static method. Both of these examples are valid:

int main(){  A* a1 = new A;  a1->doSth();  delete a1;  A a2;  a2.doSth();}

In the first case, I allocate a1 on the heap, call doSth on it (using the arrow -> syntax, because it's a pointer to an object), and then I delete it.

In the second case, I allocate a2 on the stack, call doSth on it (using the dot . syntax, because it's the actual object). (I don't need to delete it, because stack-allocated objects are destroyed when the function or method returns).

Now for something totally different.

A static method in C++ is a function contained inside of a class. They work very similarly to functions in C (like printf or fopen).

To contrast them, a non-static method is a function inside of a class that operates on a calling object. Non-static methods are invoked with the dot (.) or arrow (->) syntax. They work just like regular functions, except that the object they are called on is passed implicitly as a parameter (called "this" in C++). Inside of a method, if a variable isn't defined elsewhere, it's assumed that you meant "this->(variable name)".

Generally, you want to make MOST of your methods non-static.

1. 1
2. 2
Rutin
24
3. 3
JoeJ
19
4. 4
5. 5
gaxio
13

• 17
• 40
• 23
• 13
• 13
• ### Forum Statistics

• Total Topics
631731
• Total Posts
3001922
×