TheNVP TheNVP - 1 month ago 22
C++ Question

Composition error in c++

Newbie to C++ over here. I am trying to create 2 classes and interlink them using Composition, but I keep getting errors.

#include <iostream>
#include <string>
using namespace std;

class student
{
public: int roll_no;
string name;
string dob;
void student_display()
{
cout<<roll_no<< " "<<name<<" "<<dob<<endl;
}
student(int roll,string names,string dateofb)
{
roll_no=roll;
name=names;
dob=dateofb;
}
~student(){};
};

class course
{
public:string course_name;
int duration;

void course_display()
{
cout<<course_name<< " "<<duration<<" "<<endl;

s1.student_display()<<endl;
}
course (string c_name,int dur,student s2):course_name(c_name),duration(dur),s1(s2){}
~course(){};
private : student s1;

};

class college
{
public: string college_name;
string location;
course c1;
course (string col_name,string loc,course c2):college_name(col_name),location(loc),c1(c2){}

~course(){};
};
int main() {
student s5(001,"Noel","28/04/1994");
s5.student_display();
course c1("Engineering",4,s5(001,"Noel","28/04/1994"));
c1.course_display();
return 0;
}


The errors are as follows:

prog.cpp: In member function 'void course::course_display()':
prog.cpp:32:35: error: invalid operands of types 'void' and '<unresolved overloaded function type>' to binary 'operator<<'
s1.student_display()<<endl;
^
prog.cpp: At global scope:
prog.cpp:45:20: error: expected ')' before 'col_name'
course (string col_name,string loc,course c2):college_name(col_name),location(loc),c1(c2){}
^
prog.cpp:47:13: error: declaration of '~course' as member of 'college'
~course(){};
^
prog.cpp: In function 'int main()':
prog.cpp:52:54: error: no match for call to '(student) (int, const char [5], const char [11])'
course c1("Engineering",4,s5(001,"Noel","28/04/1994"));


Could someone please help me out? I have tried going through forums with the same error but cant figure it out
^

Answer

Line 30: Remove the semicolon.

Line 45: Looks like copy/paste error, should be the constructor of the college class, right? Then change the name from course to college. Same for the destructor on the following line.

Line 52: You create the object s5 2 lines above, I guess you want to pass this object to the constructor of the course object. If so then just remove the expression in the brackets after s5.