forward declaration of class does not work

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Shahrin
    New Member
    • Mar 2010
    • 1

    #1

    forward declaration of class does not work

    #include<iostre am>
    using namespace std;

    class teacher;

    class student
    {
    int dept;

    public:


    student(int d)
    {
    dept=d;
    }

    bool TsameDept (teacher tch)
    {
    if (dept==tch.getD ept())
    return true;
    else
    return false;
    }
    };

    class teacher
    {
    int dept;

    public:

    teacher(int d)
    {
    dept=d;
    }
    int getDept()
    {
    return dept;
    }
    };




    void main()
    {
    student st(5);
    teacher tch(5);

    if (st.TsameDept(t ch)==true)
    cout<<"Same";

    else cout<<"Differen t";
    }

    can anybody pls help

    why this program shows compile error------use of undefined type 'teacher' or left of '.getDept' must have class/struct/union type

    though I forward declared the teacher class.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    You can only use a forward reference for a pointer to a class object.

    That is, this code:

    Code:
    class MyClass;
    is sufficient for the compiler to allow:

    Code:
    MyClass* ptr;

    Anything beyond that you will be required to supply the class definition.

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      You can use them for references to

      Code:
      MyClass& ref;
      What you can't do is use it o declare an object or access any member of the class.

      Comment

      Working...