1

If I have a test code :

Number const * n = nullptr;
double val = 0;
std::cin >> val;
n = new Integer( int( val ));
if( n->intValue() != int( val )) {
                std::cout << "intValue() is wrong\n";
}

and I have a class Integer, to be able to evaluate n->intValue(), does it mean that I have to create a method call intValue( ) in the class Integer?

I tried to create a methode but it shows error 'const class Number' has no member named 'intValue'.

My class code :

#include <iostream>

using namespace std;

// Base class Number
class Number{
   public:
      Number(double theVal){
            val = theVal;
            cout << "Created a number with value " << val << endl;
      }
    protected:
      double val;
};

class Integer : public Number{
    public :
        Integer(int val):Number(val){\
        cout << "Created an integer with value " << val << endl;
         }

        int intValue(){
            return (int)val;
        }
        double doubleValue(){
            return (double)val;
        }

};

class Double : public Number{
    public :
        Double(double val):Number(val){
        cout << "Created a double with value " << val << endl;}

        int intValue(){
            return (int)val;
        }
        double doubleValue(){
            return (double)val;
        }
};
rocknoos
  • 35
  • 6

1 Answers1

1

I guess n is of type Number*, so the compiler cannot know, if it is one of the child classes beforehand. You can add

virtual int intValue() = 0;

to your parent class. See pure virtual functions here

LeoE
  • 2,054
  • 1
  • 11
  • 29
  • Could be done, but this function is meaningless for and yet must be included in `class Double` or `class complex`. Recommended reading: https://stackoverflow.com/questions/56860/what-is-an-example-of-the-liskov-substitution-principle – user4581301 Sep 16 '19 at 18:44
  • Thanks, haven't read this before, really good reading. But rocknoos has the funciton `int intValue()` in the Double class as well, so a pure virtual void could be used here. But yes, I would not do it either. – LeoE Sep 17 '19 at 09:37