Variables & Headers Question

Hey,

I have 2 simple Questions...

1 Question)

Where would you declare a local variable for a class?:

in the header?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class x{

private:
int y;

public:
};

or in the source file?

#include "x.h"

int y;

public X::X()
{
};

I'm always using the first one, also if it's an object:

1
2
3
4
5
6
7
8
9
10
11
class x{
private:
ClassY obj;
public:
 x();
};

X::X() : obj(new ClassY)
{
}


2 Question:

Where do you guys include headers, which you need for your class.
in the header file or source file?

At the moment, I Only include headers in the header if I already need them there.
Otherwise I put all includes in the source file.
1) This is really a design decision. Is the variable supposed to be part of the state of an instance of the class? Then it should be a non-static data member of the class, as in your first example.

The second example is defining a global variable, not a member of the class. Global variables should be avoided wherever possible.

2) As a general rule, you should reduce unnecessary coupling by including header files only where they are needed. So it sounds as though you're doing it right.
> Where would you declare a local variable for a class?

If it is an instance variable (one for each object instance), it has to be declared in the class as a non static member.

If it is a shared variable (common to all object instances),
either declare it as a static member of the class (and define it in the implementation file)
or define it as a non member with internal linkage in the implementation file.

Header:
1
2
3
4
5
6
7
8
9
struct account
{
    unsigned int number ; // instance variable
    // each instance of account has its own number, 
    // different accounts have different numbers.

    static const double rate_of_interest ; // static variable
    // all instances of account share a common rate of interest.
};


Implementation:
const double account::rate_of_interest = 8.3 ;


> At the moment, I Only include headers in the header if I already need them there.
> Otherwise I put all includes in the source file.

Yes, that is the way we do it too. As far as possible, we avoid gratuitous inclusion of one header in another header.
Registered users can post here. Sign in or register to post.