ddavis
ddavis

Reputation: 357

Returning member object with a getter function as const but it is modifiable

I have a class with a private member that is an object and I have set up a corresponding getter:

class lepton {
private:
  TLorentzVector _p;
  ...

public:
  ...
  const TLorentzVector& p() const { return _p; }
};

and the TLorentzVector class of course has its own functions and variables, let's say that SetStuff(...) is a function, for example. Let's also say that SetStuff(...) modifies the object's private variables. My program is allowing me to call:

....
lepton foo;
foo.p().SetStuff(...);
....

I'm wondering how this is possible given that the getter p() is const. Is this a bad way to have a getter which allows for modification of the class member? I ended up with this setup because at another point in my program I want to add the _p (TLorentzVector object) variable of two objects like so:

lepton lep1;
lepton lep2;
....
auto combined_four_vector = lep1.p() + lep2.p();
....

And if I just had the getter in the lepton class defined as:

TLorentzVector& p() { return _p; }

I am not able to add the TLorentzVector objects.

Upvotes: 1

Views: 148

Answers (1)

Shoe
Shoe

Reputation: 76260

You can define a non-constant overload and a constant overload (unless you have any reason not to define a non-constant overload):

class lepton {
    // ...
public:
    // ...
    TLorentzVector const& p() const { return _p; }
    TLorentzVector& p() { return _p; }
};

In this way for functions and operators that take a lepton const& only the const overload will be available, maintaining the const-safety of the object.


For example, the following will work as expected:

lepton foo;
foo.p().SetStuff(...);

and assuming an operator+ defined on TLorentzVector const&, the following will also work just fine:

auto res = lep1.p() + lep2.p();

Upvotes: 3

Related Questions