user1240679
user1240679

Reputation: 6979

Using a static class in C++

I have some mathematical methods (for eg: point finders, normalizing etc.) in my C++ project that probably could be used in different classes or different places in the project.

I come from a C# background and had a confusion if in such a case, I should make something like a static class that contains all these methods and use them in the program? Or should I define a class and use it via class object everywhere I want to?

What would be ideal in this case?

Upvotes: 1

Views: 137

Answers (4)

Pete Becker
Pete Becker

Reputation: 76245

Use a namespace. Sticking a bunch of static functions inside a class whose sole purpose is to group them together is a Java hack to make up for its lack of namespaces.

Upvotes: 2

Matt
Matt

Reputation: 6050

in C++, you can define a class, in this class, you define these methods as public static, the you can use it everywhere. For example:

class Mathematical
{
 public:
   static void normalize();
}

you can use the function as:

Mathematical::normalize().

It is same as the static class function in C#

Upvotes: 3

SomeWittyUsername
SomeWittyUsername

Reputation: 18348

If there is no relation between the methods you should either define them as public static funcs inside a class or as regular funcs in a dedicated namespace. Both ways it will just define a scope for your methods.

Upvotes: 4

MasterMastic
MasterMastic

Reputation: 21286

Well, I think it depends on your work, so I can't give you a concrete answer without you specifying a little bit more.

As you said, you can write it in more than one place, and it will work, so the compiler will be pleased. Now we need to please you - the programmer.

So just ask yourself "where should it be?". The answer that will come to mind is the one that will make sense.

About math operations: I think they should have their own class with static methods (and not a static-class; look at the note below), unless they're being used only in one type. If they're used in only one type it should be (typically) better to put it inside that type, even as non-static method.

Note: C++ doesn't support the static classes you have in C# (unless you use managed C++ of course)

Upvotes: 1

Related Questions