
Q1: How does avg_score function work?
Q2: How does this function, grade::grade(grade &rg) work?
Q1: How does avg_score function work? A1: On page 14 of PA #8 handout look at Step g), 2nd paragraph Here's some pseudo code. main() { Grade g1, g2; g1.avg_score(g2); } void Grade:: avg_score (Grade g) { sum of g.total + total; // Add g1 and g2' total member sum /= 2; // Average of 2 values cout << "Average is : " << sum; }
Q2: How does this function, grade::grade(grade &rg) work? A2: This is the Copy constructor a) When is a constructor called? Upon object instantiation (declaration) b) When is a copy constructor called? The newly instantiated object is being initialized with another object of its type. eg. Newly instantiated object (joe) is being initialized with another object (john) of its type (Person). class Person { int age; public: Person(void) { age = 19; } Person(Person p) { age = p.age; } //Pass john to "p" }; Person john; // Calls default ctor (sets age to 19) Person joe(john); // Calls copy ctor // (initialize joe with john's age of 19) c) So the copy constructor is called on "pass by value" for any function call passing a class object. " g1.avg_score (g2); " Therefore a copy of g2 is passed to avg_score and it's values are assigned to the formal parameter "g" in void Grade:: avg_score (Grade g) {...}
HOME || Course Description || Course Outline || Lab Hours || FAQ