Posts

Showing posts from March, 2018

Operator Overloading

// Operator Overloading #include <iostream> using namespace std; class Complex { private: float real; float img; public: Complex() { real = img = 0; } Complex(float real, float img) { this->real = real; this->img = img; } // Complex add(Complex c) // { // Complex tmp; // tmp.real = this->real + c.real; // tmp.img = this->img + c.img; // return tmp; // } // Opertors which cannot be oberloaded // ::, ., .*, ?: Complex operator +(Complex c) { Complex tmp; tmp.real = this->real + c.real; tmp.img = this->img + c.img; return tmp; } Complex operator -(Complex c) { Complex tmp; tmp.real = this->real - c.real; tmp.img = this->img - c.img; return tmp; } void display() { cout << this->real << " + " << this->img << "i" << endl; } }; int main() { Complex c1(10.5, 20.5), c2(9.3, 3.5), c3; // c3 = ...

Single Level Inheritance

#include <iostream> using namespace std; /*  * Types:  * 1. Single-Level Inheritance  * 2. Multi-level  * 3. Multiple  * 4. Hybrid  */ class Shape { private:   float width;   float height; public:   Shape()   {     this->width = this->height = 0.0;   }   Shape(float width, float height)   {     this->width = width;     this->height = height;   }   float get_width()   {     return this->width;   }   float get_height()   {     return this->height;   }   float getArea()   {     return this->width * this->height;   } }; class Square : public Shape { public:   Square() { }   Square(float side) : Shape(side, side)   {   }   float getPerimeter()   {     return 2 * this->get_width() + 2 * this-...

Constructors while inheritance

#include <iostream> #include <string.h> using namespace std; class A { public:   A()   {     cout << "A's constructor" << endl;   }   A(string s)   {     cout <<  "A's " << s << endl;   } }; class B : public A { public:   B()   {     cout << "B's constructor" << endl;   }   B(string s) : A(s)   {     cout << "B's " << s << endl;   } }; class C : public B { public:   C()   {     cout << "C's constructor" << endl;   }   C(string s) : B(s)   {     cout << "C's " << s << endl;   } }; int main(int argc, char const *argv[]) {   C c("Hello");   return 0; }