When forward declarations of functions work in a source file (.cpp), why would the same doesn't work for classes ?
Thanks.
// main.cpp
void forwardDeclaredFunction() ; // This is correct
class One ; // Why this would be wrong
int One:: statVar = 10 ;
void
One :: anyAccess() {
std::cout << "\n statVar:\t " << statVar ;
std::cout << "\n classVar:\t" << classVar ;
}
class One {
public:
void anyAccess() ;
static int statVar ;
private:
int classVar ;
} ;
int main (int argc, char * const argv[]) {
One *obj = new One ;
return 0;
}
void forwardDeclaredFunction() {
}
Forward declaration can work for classes too:
class Foo;
class Bar {
public:
Foo *myFoo; // This has to be a pointer, thanks for catching this!
};
class Foo {
public:
int value;
};
The above code shows a forward declaration of the Foo class, using a variable of type Foo* in another class (Bar), then the actual definition of the Foo class. C++ doesn't care if you leave things unimplemented as long as you implement them before using its code. Defining pointers to objects of a certain type is not "using its code."
Quick, dirty reply but I hope it helps.
Edit: Declaring a non-pointer variable of a class thats unimplemented will NOT compile as the replies stated out. Doing so is exactly what I meant by "using its code." In this case, the Foo constructor would be called whenever the Bar constructor is called, given that it has a member variable of type Foo. Since the compiler doesn't know that you plan on implementing Foo later on, it will throw an error. Sorry for my mistake ;).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With