2

I'm not sure of the proper terminology here so I'm having trouble finding the answer to my question but here is what I want to achieve.

say I have

class ABC {
public:
    int number;
};

and I want to add a function inside int number's scope (I think is how you would say it). something like IsNeg() but I would like to use it like so:

ABC abc;
abc.number.IsNeg();

which would return true or false. Would something like this be possible?

2
  • 1
    The term you are looking for is "extension method" (at least that's what it's called in C#). I do not know if C++ has that functionality, though a quick Google search gives a few hits that look promising.
    – Mage Xy
    Apr 7, 2016 at 15:22
  • If you make number a class or struct, then you could have number.IsNeg() and something like number.value to get the int.
    – Erik Eidt
    Apr 7, 2016 at 16:41

3 Answers 3

3

The behaviour should be inside the class, so you do not need these nested . calls.

The following design delivers exactly what you want without adding special complexity of a custom class representing a value.

class ABC
{
public:
    int number;

    bool isNumberNegative() const
    {
        return number < 0;
    }
};

// ... //

ABC abc;
auto isNegative = abc.isNumberNegative();

This suggested solution is also in terms with the Law of Demeter.

0
1

The short answer is no (take a look at Extension methods in c++ and C++ Extension functions? for more details).

For operators that haven't been already defined by a class you can write overloads which work on that class and it's a little like method extensions.

However the "everything is an object paradigm" doesn't hold in C++ and free functions (What's In a Class?) / Koenig lookup / namespaces are the C++ way.


In your example, you could:

  • add a member function as in David Packer's answer (number should probably be private)
  • make number a class or struct (Erik Eidt's comment)
  • make class ABC a struct and work directly on the number data member
  • write a free function

    bool is_neg(const ABC &abc)
    {
      return abc.number < 0;
    }
    
0

Practically, this cannot be done with your piece of code. Because, C++ doesn't provide primitive types as class. Hence, abc.number.IsNeg() is not possible.

You can achieve it using the code given below. But I will not recommend this, instead follow @David's advice to avoid complexity.

class ABC {
public:
    Number number;
}
class Number {
public:
    int data;
    bool IsNeg() {
        return data < 0;
    }
}

Now you can write this:

ABC abc;
abc.number.IsNeg();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.