Tutorial 03
Tutorial 03
Signer:: singTogether(Singer s)
{
cout << name << “ : Do Re Me Fa So” << endl;
cout << s.name << “ : So Fa Me Re Do” << endl;
};
Syntax
Declaration of derived class
class derived_class_name : access_control_label base_class_name
{ ……..
};
Can we write new data member and member function in the sub-
class?
Yes, just simple.
Can we write our own print() function in the LaserPrinter?
Yes, by over-ridding.
What is the different between Over-ridding and Overloading?
Overloading is different functions in a class with same function name but
different parameter list
Over-ridding is using a sub-class function to replace the base-class function.
It makes a sub-class inherit the base-class characteristics while new
characteristics can be added.
};
int main()
Public Inheritance: Protected Inheritance:
{
class LaserPrinter : protected MessagePrinter
LaserPrinter LPT1(“Hello World”,1);
{
cout << LPT1.serial_number << endl;
public:
cout << LPT1.repeat << endl;
LaserPrinter(string m, int r):MessagePrinter()
LPT1.print();
{
}
serial_number = 9999;
repeat = 3;
// ...
};
void my_print() NOT
Not OK { OK
OK
print();
};
}; OK
int main()
Private Inheritance:
{ So, what is the different between the
LaserPrinter LPT1(“Hello World”,1); protected and private inheritance?
cout << LPT1.serial_number << endl;
cout << LPT1.repeat << endl;
LPT1.print(); In protected inheritance, “repeat” and
} “print()”can be further accessed by the
sub-class of LaserPrinter, such as
HP_4L.
int caller()
{
double ratio(int a, int b){ double r = ratio(-1,0);
if(a<0||b<0) return -1; if (r == -1)
else if(b==0) return -2; cout<<”Negative Error" << endl;
else return (a/b); else if(r == -2)
} cout<<”Zero Error" << endl;
else cout << r << endl;
}
Prepared by Brian Lam Tak Cheung 20
Exception Handling
The previous code reduces the readability and may not the be the best
place to handle error here.
In C++ we use exception:
when a program detects an anomaly, an exception object is throw
throw behaves like a return statement
the object returned is caught by a try and catch block
In summary:
create an exception object at point of exception
pass (throw) the exception back to caller
if the caller cannot handle it, then pass (rethrow) the object to a higher
level caller
eventually back to main
if main cannot handle it, throw the object to system
program is terminated