Home > Blockchain >  Declaration of class inside header file without initialization
Declaration of class inside header file without initialization

Time:10-30

I want to declarate a class object of Class B inside of Class A in a header file, like:

// test.h

class A {
public:
    B b;
    
};

but lets say B has no default Constructor and the required parameters are not known yet (in header file). Which possibilities in c exist to declarate a class instance in another class without initializing it at that moment.

CodePudding user response:

Your example lacks any declaration of B, so you will get a compiler error. You must either add or include B's declaration, or you will need to forward declare it, e.g.

class B;

class A {
public:
    B b;  // Compiler error
};

However, this will still not work, since A needs to know the space to set aside for B. You may work around this, by making b a reference, pointer or smart pointer to B:

class B;

class A {
public:
    A();
    B* b1;
    B& b2;
    std::unique_ptr<B> b3;
};

For b1, b2 and b3, it is enough that you include the declaration of B in A's .cpp file and initialize the B's there:

// A.cpp

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

A::A() : b1(new B(<params>)), b2(<from a reference>), b3(make_unique<B>(params)
{}

Note that b1 is bad, since it uses new and needs to delete the object later, and that b3 will need a destructor defined in A.cpp (the default is fine).

CodePudding user response:

You need to initialize it. You need to, at least, declare it: class B.

  •  Tags:  
  • c
  • Related