c++ - Constructor can only be defined outside class -


in following code, constructor can defined outside class, or compiler give errors.

class student; class teacher  { private:     int num;     string name;     string sex;     string title; public:     teacher(student &s) {         num=s.num ;         name=s.name ;         sex=s.sex ;     }     void display(); };  class student { public:     int num;     string name;       string sex;     float grade;     friend teacher;     void set_student(); };  void teacher::display() {     cout<<num<<" "<<name<<" "<<sex<<endl; }    void student::set_student()  {      cin>>num>>name>>sex>>grade; }    int main() {     student s1;     s1.set_student() ;     teacher t1(s1);       t1.display() ;     return 0; } 

it didn't compile, if move definition of constructor outside class, compiles:

class teacher { public: teacher(student &s); ... };  teacher::teacher(student &s) {     num=s.num ;     name=s.name ;     sex=s.sex ; }    

the error is:

floyd.cpp: in constructor 'teacher::teacher(student&)': floyd.cpp:37:8: error: invalid use of incomplete type 'class student'    num=s.num ;         ^ floyd.cpp:27:7: error: forward declaration of 'class student'  class student;        ^ floyd.cpp:38:9: error: invalid use of incomplete type 'class student'    name=s.name ;          ^ floyd.cpp:27:7: error: forward declaration of 'class student'  class student;        ^ floyd.cpp:39:8: error: invalid use of incomplete type 'class student'    sex=s.sex ;         ^ floyd.cpp:27:7: error: forward declaration of 'class student'  class student; 

why happen?

in order able compile declaration

teacher(student &s); 

the compiler needs know class student exists. forward declaration

class student; 

successfully fulfills requirement: tells compiler there going definition of class student @ later point. however, in order able compile code

teacher(student &s) {     num=s.num ;     ... } 

the compiler needs know content of student class well. specifically, needs know student has member variable num. not possible until point of program student class defined.

there 2 ways of addressing issue:

  • you discovered first 1 - move constructor definition out of class, or
  • switch order of declarations, , forward-declare teacher - possible because student's code not depend on teacher's definition.

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -