tags:

views:

102

answers:

5

I have two basic questions. The first one is about function in other classes. If I have a header file with a class in it and I want to use that function in another class I have created, do I always have to construct a class object to run a function in that class like:

someclass class; <----object construction
class.somefunction();  

Is there a way just to call the function with the object construction?

And the second question is it okay to put multiple small classes in one header file?

+3  A: 

If your function is declared static then you don't need an object instance to call it.

class Foo
{
    public:
        static void Bar() {}
};

// ...later
Foo::Bar();

To answer your second question, yes it's sometimes ok. I've done that before with small utility structs that are related to each other. Usually I'm just being lazy and don't want to bother making separate files.

Kristo
A: 

Is there a way just to call the function with the object construction?

Only if the function is declared static. (ok, that's a lie, its possible without constucting a object if you subvert the type system, but it's not a good idea)

And the second question is it okay to put multiple small classes in one header file?

Sure, it's done all of the time.

John Knoeller
+3  A: 

Functions should only be member functions if they act on an object of the class. Functions that don't act on an object should just be plain global functions (or class static):

// Global function
void foo() { /* do something */ } 

// Static function
class Foo
{
public:
  static void foo() { /* do something */ }
};

For your second question, yes it's ok. Generally people stick to one class per file, but in my opinion there's nothing wrong with having a few small classes in a single file.

Peter Alexander
You (or someone you're learning from) may be coming from a Java background, where all functions have to go into a class. In C++ there is no such restriction so you should feel completely free to write functions that are outside of a class, if it makes more sense that way.
MatrixFrog
I think you meant to comment on the question post.
Peter Alexander
A: 

1 static as already mentioned

2 do what feels natural. Keep related classes together. One of the problems with JAva is its fanatical enforcement of one class per file

However - unforgivable sin is spreading the implementation of class a throughout the implementations of classes b c and d

Ie all of a class implementation should be in one .cpp file.

pm100
A: 
  1. delcare the function as static.
  2. Are you talking about inner classes? If thats the case, then its totally legit.
tommy-susanto