FinalExamSolutionsFa08

FinalExamSolutionsFa08 - Fa08 CS31 Disc 1B – Week 10...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
1 Fa08 CS31 Disc 1B – Final Exam Practice Solutions TA: Peter Wu ( peterhwu@cs.ucla.edu ) Webpage: http://www.cs.ucla.edu/~peterhwu/cs31/ 1. IceBreakers! It's the last day of class, and we want you to write your name, major, and year, all a class declaration. Here's the following class: const int LENGTH = 10; class Student { public : // constructors Student( char firstName[], char * lastName, int year, string major); Student(); // fills in all member variables with "" or 0 // accessors int getYear() const ; //implemented string getMajor() const ; //implemented string getFirstName() const ; //implemented string getLastName() const ; //implemented // mutators bool changeMajor(string major); void changeFirstName(char* newName); private : int m_year; string m_major; char m_name[2][LENGTH+1]; }; (a) Constructors. Write the first constructor. For this question only, the constructor should also print to screen a "Welcome, <firstName>" message. For the other questions, we're going to assume the constructor doesn't print anything. Student::Student(char* firstName, char* lastName, int year, string major) { strcpy(m_name[0], firstName); strcpy(m_name[1], lastName); m_year = year; m_major = major; cout << "Welcome, " << firstName << endl; } (b) Constructors. What do each of the following statements do? (compile-time error, run-time error, or describe result) Student s1; Student s2( "Joe" , "Bruin" , 1, "computer science" ); Student *s3( "Joe" , "Bruin" , 1, "computer science" ); // compile error (CE) Student s4 = new Student(); // CE: should be a pointer Student s5 = new Student( "Joe" , "Bruin" , 1, "computer science" ); // CE: should be a pointer Let's say we remove the default constructor from the class, so that we're only left with the 4-argument constructor. What happens if we run the statement: Student s1; ? Compile error, because the compiler can't find the default constructor for the class Remember that the call to the default constructor has no parenthesis. (c) Accessing fields. Assuming that we have both constructors, we now have:
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/07/2010 for the course CS 190-001-20 taught by Professor Hashiguchi during the Fall '09 term at UCLA.

Page1 / 5

FinalExamSolutionsFa08 - Fa08 CS31 Disc 1B – Week 10...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online