0

I have base class Array in which I have virtual function Add for addition

class Array
{
public:
    unsigned char arr[100] = { 0 };
    int size;
    Array();
    Array(int);
    char operator[](int);
    virtual Array& Add( Array);
};

I have two derived classes Hex ( for storing hexidecimal numbers ) and BitString( for storing binary numbers ):

class BitString : public Array
{
public:
    BitString& operator&(BitString&);//and
    BitString& operator|(BitString&);//or
    BitString& operator^(BitString&);//xor
    BitString& operator~();//not
};

class Hex: public Array
{
public:
    Hex& operator+(Hex);
    Hex& operator-(Hex);
    Hex& operator*(Hex);
    Hex& operator/(Hex);
    bool operator==(const Hex);
    bool operator>(const Hex);
    bool operator<(const Hex);
    Hex DecToHex(int);
};

My task, except make operators for Hex and BitString, is to override virtual Add function for addition BitString and Hex objects.

I dont properly get :

1) Need I make 2 functions in both Hex and BitString

2) What these functions should return? Hex, BitString or Array.

3) What is the fastest way to do this? Convert both Hex and BitString to decimals, make addition and then convert again?

Thank you.

HK boy
  • 1,398
  • 11
  • 17
  • 25
Tovarisch
  • 39
  • 2
  • 13
  • 1
    Can you elaborate about storing hex or binary numbers? They are just numbers using a different representation. There's a number of ways to present their representation as hex, binary, octal or decimal digits. – πάντα ῥεῖ May 26 '19 at 10:47
  • OT: make all those operator overloads `const`, return by value and take `const&` parameters, not all mixed up like it is now. Because none of those functions should modify anything. For that visit https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading. – LogicStuff May 26 '19 at 10:57

1 Answers1

1

Since your classes are polymorphic, the Add() function should be taking a reference or pointer parameter:

class Array {
    // ...

    virtual Array& Add(Array&);
};

You can now override Add() in your derived classes with a different return type:

class Hex: public Array {
    // ...

    Hex& Add(Array&) override;
};

The return type must be a reference type of the class that does the override. This is the only case where an override can change the return type.

Nikos C.
  • 50,738
  • 9
  • 71
  • 96