/* Author: Arun Somasundaram, CSE, OSU Simple program to test 1. Virtual/Pure Virtual Functions 2. Polymorphism 3. Abstract classes */ #include using namespace std; //---------------------Base Class-------------------// class Base{ private: int b; public: Base(){b = 10;} Base(int bVal); virtual ~Base(); //Destructor is virtual. Why? void setVal(int bVal){b = bVal;} //inline virtual void printVal(); //virtual function }; Base::Base(int bVal){ b = bVal; } Base::~Base(){ cout << "Base destructor is called" << endl; } void Base::printVal(){ cout << "The value of Base object is " << b << endl; } //--------------------Deriv Class----------------------// class Deriv:public Base{ private: int d; public: Deriv(){d = 20;} Deriv(int dVal); virtual ~Deriv(); //Destructor is virtual. Why? void setVal(int dVal) {d = dVal;} //inline virtual void printVal(); //virtual function }; Deriv::Deriv(int dVal){ d = dVal; } Deriv::~Deriv(){ cout << "Deriv destructor is called" << endl; } void Deriv::printVal(){ cout << "The value of Deriv object is " << d << endl; } //-------------------General Print Functions-------------------// void print(Base b){ //Note that the argument of the function is not a pointer nor a reference type b.printVal(); } void printUsingPtr(Base * b){ //The argument of this function is a pointer to the base class Base. Why not the derived class? //For polymorphism, pointers or reference variables should be used. b->printVal(); } void printUsingRef(Base &b){ //The argument of this function is a reference to the base class Base. Why not the derived class? //For polymorphism, pointers or reference variables should be used. b.printVal(); } //-------------------Shape Abstract Class-------------// class Shape{ //Abstract Class - Why? public: virtual void draw()=0; //Pure Virtual Function }; class Triangle:public Shape{ //Also an Abstract Class - Why? public: void print(){ cout << "This is a triangle" << endl; } }; class Rectangle:public Shape{//Not a Abstract Class - Why? public: void draw(){ cout << "Drawing a Rectangle" << endl; } }; //----------------- main function---------------------// int main(){ Base b(100); Deriv d(200); cout << endl << "Passing objects..." << endl; print(b); print(d); // What happens here? Why? cout << endl; cout << "Passing Pointers..." << endl; Base *bP; bP = &b; printUsingPtr(bP); bP = &d; printUsingPtr(bP); //What happens here? Why? cout << endl; cout << "Passing References..." << endl; printUsingRef(b); printUsingRef(d); //what happens here? Why? cout << endl; cout << "Abstract Classes" << endl; //Triangle t; //Error! Why? Rectangle r; r.draw(); cout << endl; }