Class: Special Topics Overloading (methods) Copy Constructors Static members
Overloading (methods) The same function (i.e. function name) can be defined multiple times in a class. but, each definition must have a different list of parameters The compiler decides which to use based on the argument list Considerations Number of arguments Types of arguments Inheritance Lower-level method will be chosen over a higher level
Method overloading (type based) class PrintData { public: void print(int i) { cout << "Printing int: " << i << endl; } void print(double f) { cout << "Printing float: " << f << endl; void print(string c) { cout << "Printing string: " << c << endl; }; int main(void) { printData pd; // Call print to print integer pd.print(5); // Call print to print float pd.print(500.263); // Call print to print string pd.print("Hello C++"); return 0; }
Method overloading (number based) class PrintData { public: void print(int i) { cout << "Printing int: " << i << endl; } void print(int i, int j) { cout << "Printing 2 ints: " << i << “ “ << j << endl; }; int main(void) { PrintData pd; // Call print to print integer pd.print(5); // Call print to print two integers pd.print(5,10); return 0; } Examples: FuncOver and Person
Copy constructor Example: General/Date A copy constructor is a special constructor that takes a class instance of the same type as an argument It is called automatically when the compiler needs to make a copy of a class instance Ex: when passing a class instance to a function “by value” Input argument should always be a const reference MyClass(const MyClass&); const ensures that the argument will not be modified Reference ensures that the argument will not be copied Otherwise, the copy constructor would be called again to make the copy Infinite loop!!!! Example: General/Date
Static members A static member of a class is specified using the keyword static static const string seasons[]; // in header file ClassName::seasons[]= { “spring”, “summer”, “winter”, “fall” }; // in .cpp file Member functions can also be static! Static members do not belong to any instance of the class They are “global” Static members are accessed using the class name directly string now= ClassName::seasons[2]; An instance is not required (no “.” operator!) – and should not be used Example: General/Date