Answer to Question #186900 in C++ for saurav kumar

Question #186900

 Explain the type of polymorphism with code 


1
Expert's answer
2021-04-28T23:29:00-0400
//C++ program to demonstrate compile time polymorphism using operator overloading
#include <iostream>

using namespace std;

class A
{
  private:
    int count;
  public:
    A() : count(10) {}
    void operator --()
    {
      count = count - 3;
    }
    void display()
    {
      cout << "Count: " << count;
    }
};

int main()
{
	A a;
	--a; //Decrement operator has been overloaded to work on object
	a.display();
	return 0;
}


//C++ program to demonstrate runtime polymorphism
#include <iostream>

using namespace std;

class Parent
{
public:
  virtual void print() //Parent virtual function
  {
    cout << "Print parent class" << endl;
  }

  void show()
  {
    cout << "Show parent class" << endl;
  }
};


class Child : public Parent {
  public:
    void print()
    {
      cout << "Print child class"<< endl;
    }

    void show()
    {
      cout << "Show parent class"<< endl;
    }
};

int main()
{
  Parent* pptr;
  Child c;
  pptr = &c;

  // Virtual function bound at run time
  pptr->print();

  // Non virtual function bound at compile time
  pptr->show();
}
 

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS