Reputation: 531
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
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:
Upvotes: 1
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