Question #187300

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 Armstrong is derived from


class called Number. Another class called Palindrome is derived from class Number. Use


appropriate constructors and redefine the function called operation to display if the number is


Armstrong number as well as Palindrome in case it falls in this category. You may make use of


other data members and member functions if needed



Expert's answer

#include <iostream>
#include <string>
using namespace std;
class Number{
    protected:
        int x;
    public:
        Number(){}
        virtual void operation(){};
};
class Armstrong: public Number{
    public:
        Armstrong(int y){
            x = y;
        }
        bool is_armstrong(){
            string s = to_string(x);
            int sum = 0, temp;
            for(int i = 0; i < s.length(); i++){
                temp = s[i] - '0';
                sum += temp * temp * temp;
            }
            if(sum == x) return true;
            else return false;
        }
        void operation(){
            if(is_armstrong()) cout<<x<<" is armstrong\n";
            else cout<<x<<" is not armstrong\n";
        }
};
class Palindrome: public Number{
    public:
        Palindrome(int y){
            x = y;
        }
        bool is_palindrome(){
            string s = to_string(x);
            for(int i = 0, j = s.length() - 1; i < s.length() / 2; i++, j--){
                if(s[i] != s[j]) return false;
            }
            return true;
        }
        void operation(){
            if(is_palindrome()){
                cout<<x<<" is palindrome\n";
            }
            else cout<<x<<" is not palindrome\n";
        }
};
int main(){
    Number *number;
    int x;
    cout<<"Enter number to analyze: ";
    cin>>x;
    number = new Armstrong(x);
    number->operation();
    number = new Palindrome(x);
    number->operation();
    return 0;
}
LATEST TUTORIALS
APPROVED BY CLIENTS