简体   繁体   中英

Declaration of class inside header file without initialization

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.

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

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, eg

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 ba 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM