Click to See Complete Forum and Search --> : Forward Declaration


GotToDream
June 18th, 2008, 09:35 PM
I have a class Rule and another class Condition. Rule.hh file has a pointer declaration to Condition class. The definition looks like -

//--------------------- Rule.hh ------------------
#ifndef __RULE_HH__
#define __RULE_HH__

#include <iostream>
#include "Condition.hh"

class Condition;

class Rule {
public:
void Condition( const char* );
private:
Condition *condition;
}

//----------------------- Rule.cc -------------
void
Rule::Condition( const char *c) {
condition = new Condition( c );
}

And then Condition class is defined in Condition.hh file.

Problem - Even though I forward declare Condition class in Rule.hh, I am getting an error while compiling -
"ISO C++ forbids declaration of 'Condition' with no type"
"expected ';' before '*' token"

Can someone please help me solve this problem?

Plasmator
June 18th, 2008, 09:49 PM
My eyes are bleeding. Use code-tags, please.

Can someone please help me solve this problem?You're doing this:

class Foo {};

class Bar
{
void Foo() {}

Foo foo;
};
You're confusing the compiler. Change "void Rule::Condition( const char* );" and you'll be set.

GotToDream
June 18th, 2008, 10:21 PM
Thanks. That obviously worked. Feeling bad for wasting time on a silly mistake.

souldog
June 19th, 2008, 12:44 AM
also it appears that you are both forward declaring condition and including condition.h in rule.h. You don't need to do both, in fact the forward declaration is pointless if you also include condition.h

GotToDream
June 19th, 2008, 08:58 PM
Right. But I do a condition = new Condition() in Rule.cc file. So when I comment the #include "Condition.hh" statement, I get an error
"invalid use of undefined type 'struct Condition'"
"forward declaration of 'struct Condition'

Do you know why I am getting this error?

code_carnage
June 20th, 2008, 01:37 AM
I think you can not do because compilar would not be able to see the contructor you are invoking by calling new.

Now you have to provide declaration for constructor as well..


So better when you are writting defnition that is CPP include .h file and not forward declaration.. While if you are creating writting header file you can use forward declaration.


MYclass1.h

class HelloPrashant //in header file use forward declaration.

class MyClasss1
{
...
....
private:
HelloPrashant* h;
}

MyClass1.cpp

#include "MYclass1.h"
#include "HelloPrashant.h" //in cpp include header file of the class

MyClass1::SomeMethod()
{
h = new HelloPrashant();
}