Xiufen Xu Xiufen Xu - 1 month ago 6
C++ Question

The ways to include another classes in a class file

I am learning c++ and confused about the ways to include another class in current class. For example, I am wondering whether

class QuackBehavior
equals to
#include <QuackBehavior.h>
. If they are equal, what are the differences between these two ways? The code is :

#include <string>

class QuackBehavior;

class Duck {
public:
Duck();
virtual ~Duck() {};

virtual void performQuack();

virtual std::string getDescription() = 0;

std::string getName() {return m_name;}
void setName(std::string name ) {m_name = name;}
void setQuackBehavior(QuackBehavior * behavior);

protected:
std::string m_name;
QuackBehavior * m_quackBehavior;

};


Thank you so much.

Tas Tas
Answer

The two are not equal:

class QuackBehavior; is considered a forward-declaration, and simply informs the compiler that there is a class called QuackBehavior. This can only be used if you are using QuackBehavior as a pointer or reference:

class B;
struct C;
struct A
{
    shared_ptr<B> getB() const { return b; }
    const C& getC() const;
private:
    shared_ptr<B> b;
};

Here the compiler doesn't need to know any implementation details of C and B, only that they exist. Notice that it's important to tell the compiler whether it's a class or struct also.

#include <QuackBehavior> is an include, and essentially copies+pastes the entire file into your file. This allows the compiler and linker to see everything about QuackBehavior. Doing this is slower, as you'll then include everything that QuackBehavior includes, and everything those files include. This can increase compile times dramatically.

Both are different, and both have their places:

  • Use forward-declaration when you don't need to know the implementation details of a class just yet, only that they exist (e.g. use in pointers and references)
  • Include the file if you are declaring an object, or you need to use functions or members of a class.
Comments