I understand that wherever possible we shall use forward declarations instead of includes to speed up the compilation.
I have a class Person like this.
#pragma once
#include <string>
class Person
{
public:
Person(std::string name, int age);
std::string GetName(void) const;
int GetAge(void) const;
private:
std::string _name;
int _age;
};
and a class Student like this
#pragma once
#include <string>
class Person;
class Student
{
public:
Student(std::string name, int age, int level = 0);
Student(const Person& person);
std::string GetName(void) const;
int GetAge(void) const;
int GetLevel(void) const;
private:
std::string _name;
int _age;
int _level;
};
In Student.h, I have a forward declaration class Person; to use Person in my conversion constructor. Fine. But I have done #include <string> to avoid compilation error while using std::string in the code. How to use forward declaration here to avoid the compilation error? Is it possible?
Thanks.
Since used
stringasthe whole structure of
stringwould be needed, so the declaration must be needed. You must#include <string>.Declaration of
stringcan be omitted possible if you write, e.g.which you could use a forward declaration, but I still recommend you not to do so, because
std::stringis not a simple structure type like Person or Student, but a very complex type involving many templates:If you forward declare it wrongly (e.g.
class string;), the compilation will fail when you actually use it because of conflicting type.