Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cassert>
- #include <stdexcept>
- using namespace std;
- // function override example
- //
- struct A
- {
- int foo() { return 1; }
- // virtual function method is overriden with the override declaration in the next structure.
- virtual int bar() { return 1; }
- virtual int divy(int a, int b) { return a/b; }
- };
- struct B : A
- {
- int foo() { return 2; }
- // override declaration makes it the master
- int bar() override { return 2; }
- int divy(int a, int b) override { return b/(2*a); }
- };
- // pointer to function example
- //
- int arithmetic(int, int, int (*)(int, int));
- // Take 3 arguments, 2 int's and a function pointer
- // int (*)(int, int), which takes two int's and return an int
- int add(int, int);
- int sub(int, int);
- int add(int n1, int n2) { return n1 + n2; }
- int sub(int n1, int n2) { return n1 - n2; }
- int arithmetic(int n1, int n2, int (*operation) (int, int)) {
- return (*operation)(n1, n2);
- }
- int main() {
- B b;
- A *a = &b;
- // it selects the A method hence value
- int v1 = a->foo();
- // override here selects the B method and hence its value
- //
- int v2 = a->bar();
- std::cout << " value v1 " << v1 << " value v2 " << v2 << std::endl;
- // add
- std::cout << arithmetic(v1, v2, add) << std::endl;
- // subtract
- std::cout << arithmetic(v1, v2, sub) << std::endl;
- assert(v1 == 1);
- assert(v2 == 2);
- A a2;
- a = &a2;
- // now its like type A only as it we set it to the address of A2
- v1 = a->foo();
- v2 = a->bar();
- std::cout << " value v1 " << v1 << " value v2 " << v2 << std::endl;
- assert(v1 == 1);
- assert(v2 == 1);
- // add
- std::cout << arithmetic(v1, v2, add) << std::endl;
- // subtract
- std::cout << arithmetic(v1, v2, sub) << std::endl;
- a = &b;
- // now we have addressed B but the return variable is a const declaration
- try {
- int v3 = a->divy(v2,0);
- std::cout << "v3 " << v3 << std::endl;
- } catch (const std::exception& e) { std::cout << e.what() << std::endl; }
- try {
- throw 20; // before we divide bv 0 throw it
- int v4 = a->divy(0,v2);
- std::cout << "v4 " << v4 << std::endl;
- }
- catch (int e)
- {
- cout << "divide by zero found first. " << e << '\n';
- }
- catch (const std::exception& e) { std::cout << e.what() << std::endl; }
- a = &a2;
- try {
- int v3 = a->divy(0,v2);
- std::cout << "v3 " << v3 << std::endl;
- } catch (const std::exception& e) { std::cout << e.what() << std::endl; }
- try {
- int v4 = a->divy(v2,0);
- throw std::runtime_error("Div zero stopped");
- std::cout << "v4 " << v4 << std::endl;
- } catch (const std::exception& e) { std::cout << e.what() << std::endl; }
- std::cout << " ended " << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement