Xiufen Xu
Xiufen Xu

Reputation: 531

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.

Upvotes: 0

Views: 67

Answers (2)

Tas
Tas

Reputation: 7111

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.

Upvotes: 1

ObliteratedJillo
ObliteratedJillo

Reputation: 5166

In QuackBehavior.h file, forwarding declaring QuackBehavior class will suffice.

#include <string>

class QuackBehavior; // tells the compiler that a class called QuackBehavior exists without any further elaborations

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;
};

However in QuackBehavior.cpp file, you have to use #include"QuackBehavior.h" so that the compiler can find the implementation member functions

#include <QuackBehavior.h> 
#include <string>
duck::duck()
{
}

Upvotes: 1

Related Questions