3

This is the constructor in the class:

Course(int courseId, Instructor instructor, string courseName, string dept) 
    : courseId(courseId)
    , instructor(instructor)
    , courseName(courseName)
    , dept(dept)
{ };

My problem is with the second argument Instructor instructor. What exactly does this mean because I have never seen mixing of two classes like this?

12
  • 1
    It means you need to have an Instructor object in order to create a Course (and a copy of that object will be stored in the created Course object) Commented Feb 22, 2014 at 19:17
  • ... same way as you need std::string instances ... Commented Feb 22, 2014 at 19:20
  • what's the problem in having Instructor object being passed in constructor? Also note you are passing Instructor object by value hence copy ctr for Instructor would be invoked here. Commented Feb 22, 2014 at 19:25
  • Can someone give a random example of what the constructor call would look like since it includes the Instructor object? Commented Feb 22, 2014 at 19:28
  • It makes it hard to read (kind of "ambiguous") when you have the same names for the arguments that you pass to the constructor and for the member variables of the class. If you can use different names for the arguments, then it will make the code easier to read and understand. Commented Feb 22, 2014 at 19:33

1 Answer 1

7

It means you need to pass an Instructor object to it, just as the first parameter means it takes an int object, and the third and fourth take string objects. For example:

int courseId = 0;
Instructor instructor; // Here we default construct an Instructor
std::string courseName = "Foo";
std::string dept = "Bar";

Course my_course(courseId, instructor, courseName, dept);
//                         ^^^^^^^^^^
//              Here the Instructor is being passed

That declaration of instructor will only work if Instructor has a default constructor, which I'm guessing it doesn't. If the constructor for Instructor has some parameters, then you need to pass them like so:

Instructor instructor(some, params, here);
Sign up to request clarification or add additional context in comments.

4 Comments

In fact you should also mention this little naming clash problem, that was discussed by @barakmano and me right above.
@πάνταῥεῖ I don't do it and I don't see a good reason to recommend it. I definitely won't recommend pre/postfixing member names! If you could come up with more appropriate names for either the parameters or the members, that would be fine, but sticking little symbols on member names is not very nice in my eyes. Their names do not need to distinguish them - they are already distinguished by being members.
OK you're right, since they (the members) are referenced from the initializer list, they're distinguished well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.