Reputation: 607
I got error:
/Users/apple/Desktop/c.cpp:9:3: error: member access into incomplete type 'const World'
w.name;
^
/Users/apple/Desktop/c.cpp:6:7: note: forward declaration of 'World'
class World;
^
1 error generated.
when run:
#include <string>
#include <iostream>
using namespace std;
class World;
void show_name(const World& w) {
cout << w.name << endl;
return;
}
class World {
public:
string name;
};
The following link provided the methods that using the class type defined later,
Defining a class member with a class type defined later in C++
But what if I want to access the member of a class that defined later and I insist this calling function defined before the definition of the class, like the example I used.
Upvotes: 0
Views: 1942
Reputation: 3321
You cannot do that. Any use of a declared but not defined class cannot access its internals or use any knowledge of them, eg size or layout. You can use World*
and World&
but not dereference them in any way.
The common way to handle this case is to define the class in a header file. That definition must define all member variables and declare member functions, but it does not need to define those functions. Now the compiler knows the internals of the class and can use it accordingly.
Here's an example of how visibility of a class affects what you can do with it.
class World;
void func(const World& w) {
std::cout << w; // Okay, only uses reference
std::cout << w.name; // error
World w2 = w1; // error, compiler needs to know that class offers copy constructor
w.do_something(); // error, compiler doesn't know what this is
}
class World {
public:
std::string name;
void do_something() const; // Doesn't need implementation to be called
}
std::ostream& operator<<(std::ostream s, const World& w) {
std::cout << w.name; // OK
w.do_something(); // OK
return s;
}
Note that World::do_something()
needs to be defined somewhere, but that could even be a separate translation unit. This mechanism allows the definition of classes in .h files and the definition of their methods in .cpp files. If no definition exists across the project, you won't get a compiler error, but you will get a linker error.
Upvotes: 2