Sign in to follow this  
arwi234

Static functions or pointers?

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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this