Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward Declaration of Class, Function

Tags:

c++

visual-c++

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() {
}
like image 718
Mahesh Avatar asked Dec 02 '10 23:12

Mahesh


1 Answers

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 ;).

like image 115
The Maniac Avatar answered Oct 06 '22 23:10

The Maniac