



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




?:
Sample: int main() { void increment (int &); int x = 2;
increment(x); //function call
return 0; }
void increment(int & y) //function prototype { y++; }
To maintain the integrity of private data members by preventing them from clients modifying through reference.
48 Student:: Student(char * n, int id) 49 { 50 name = new char [strlen(n) +1]; 51 name = n; 52 studentid = id; 53 count ++; 54 } 55 56 const char *Student:: GetName() const 57 { 58 return name; 59 } 60 61 void Student:: SetName(char * n) 62 { 63 name = new char [strlen(n) +1]; 64 name = n; 65 } 66 67 int Student:: GetId() const 68 { 69 return studentid; 70 } 71 72 void Student::SetId(int id) 73 { 74 studentid= id; 75 } 76 77 Student :: ~Student() 78 { 79 cout << "Destroying " << name << endl; 80 delete [] name; 81 count--; 82 } 83 84 //-File "main.cpp" begins here 85 86 #include "Student.h" 87 88 int main() 89 { 90 91 Student *sPtr = new Student("Phil Mickelson", 987654321); 92 93 sPtr->SetName("Tiger Woods"); 94 95 Student s2; 96 s2.SetName("Ernie Els"); 97 s2.SetId(123454321); 98 99 cout << "Number of Students:" << sPtr->count << endl; 100
101 cout << *sPtr << s2; 102 delete sPtr; 103 sPtr =0; 104 105 cout << "Number of Students:" << Student::count << endl; 106 107 return 0; 108 }
So that even if a programmer includes the header file multiple times, the compiler includes it only once.
Because such functions are not supposed to modify class members.
To hide the actual implementation; a notion popularly known as information hiding.
So that every object of Student class can access and modify the shared variable count.
To allocate memory to the character array dynamically.
strlen()
Based on Programming Assignment #2, define a function in the class Sentence which overloads operator() to return a subsentence consisting of words from index begin through end, e.g., A subsentence of sentence “Alexander Graham Bell invented telephone.” with begin=2 and end=4 is “Bell invented telephone.”
Prototype: const Sentence operator() (int begin, int end) Usage: s(2, 4);
Assume valid inputs. You may reuse the functions already defined for the class Sentence. You must create a Sentence object in your function definition.
const Sentence Sentence:: operator ()(int begin, int end) { Sentence s; for (int i=begin; i <= end; i++) s+= word[i]; return s; }