Answer to Question #188086 in C++ for Shaikh Shahid Raaz

Question #188086

Write a program which has an abstract class called Number having an integer data member. The class contains a pure virtual function called operation. A class called odd is derived from class called Number. Another class called Even is derived from class Number. Yet another class called prime is derived from Number. Use appropriate constructors and redefine the function called operation to display if the number is odd, even or prime. You may make use of other data members and member functions if needed


1
Expert's answer
2021-05-02T03:05:03-0400
#include <iostream>
#include <string>
using namespace std;
class Number{
    protected:
        int x;
    public:
        Number(){}
        virtual void operation(){};
};
class Even: public Number{
    public:
        Even(int y){
            x = y;
        }
        bool is_even(){
                
            if(x%2!=0) return true;
            else return false;
        }
        void operation(){
            if(is_even()) cout<<x<<" is even\n";
            else cout<<x<<" is not even\n";
        }
};
class Odd: public Number{
    public:
        Odd(int y){
            x = y;
        }
       bool is_odd(){
             
        if(x%2==0)     return true;
        else    return false;
        }
        void operation(){
            if(is_odd()){
                cout<<x<<" is odd\n";
            }
            else cout<<x<<" is not odd\n";
        }
};
class Prime: public Number{
    public:
        Prime(int y){
            x = y;
        }
       bool is_prime(){
            if (x == 0 || x == 1)
                return  false;
            
            for (int i = 2; i < x; i++)
                if (x % i == 0)  
                   return false;
            return true;        
       }  
       void operation(){
            if(is_prime()){
                cout<<x<<" is prime\n";
            }
            else cout<<x<<" is not prime\n";
        }
};

int main(){
    Number *number;
    int x;
    cout<<"Enter N: ";
    cin>>x;
    number = new Even(x);
    number->operation();
    number = new Odd(x);
    number->operation();
    
    number = new Prime(x);
    number->operation();    
    return 0;
}




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