C3PO C3PO - 2 months ago 6
C++ Question

Where should class objects be declared?

Should they be declared in the

.cpp
or
.h
files?

Example 1:

A.h
#include "B.h"
#include "C.h"

class A
{
void someFunction();
B b;
C c;
}


Example 2:

A.cpp
#include "B.h"
#include "C.h"

A::someFunction()
{
B b;
C c;
// Do something with b and c.
}


Example 3:

A.cpp
#include "B.h"
#include "C.h"

B b;
C c;

A::someFunction()
{
// Do something with b and c.
}


Should they only be declared in the function that is using them (example 2) or can they be declared at the top of the file under the header includes like in example 3?

Answer

All of those examples are for different use cases:

A.h
#include "B.h"
#include "C.h"

class A
{
    void someFunction();
    B   b;
    C   c;
}

This adds objects b and c of types B and C respectively to your class A. Any object of type A will now have access to these 2 other objects. (just not outside of the class since they're implcitly private). This is vastly different from example 2 & 3 since it doesn't actually define any variables yet until you instantiate an object of A.

Example 2:

A.cpp
#include "B.h"
#include "C.h"

A::someFunction()
{
    B   b;
    C   c;
    // Do something with b and c.
}

This is usually the best scenario when you only need to use b and c inside someFunction and their changes don't have to be visible to the outside of the function. Note that their lifetimes are until the end of the function.

Example 3:

A.cpp
#include "B.h"
#include "C.h"

B   b;
C   c;

A::someFunction()
{
    // Do something with b and c.
}

Here, b and c are both global variables, globals are usually frowned upon because they make it hard to track what part of your code is doing what modification to these variables. A better alternative would be passing them around and defining them in main() if their lifetime should be the for entirety of the program.

Comments