0

In my C++ class I need to assign a method with pointer and/or reference. So I do this tricky thing :

(Assuming aclass is a class variable AnotherClass *)

void MyClass::setElem(AnotherClass *pVal)
{
  aclass = pVal;
}

void MyClass::setElem(AnotherClass &refVal)
{
  aClass = &article;
}

But in my opinion, sounds not so "graceful"...

Better way to achieve this ?

Stef
  • 3,691
  • 6
  • 43
  • 58
  • 1
    I don't see how else you'd do it? Maybe you are not really explaining what you are after – Pete Jul 19 '13 at 09:30
  • It works perfectly. But to do it better we need to know WHY you do it – Emilio Garavaglia Jul 19 '13 at 09:31
  • 1
    Brother: please uncomment *`Assuming aclass is a class variable AnotherClass *aclass;`* – Grijesh Chauhan Jul 19 '13 at 09:33
  • You have removed information don't remove. – Grijesh Chauhan Jul 19 '13 at 09:35
  • @GrijeshChauhan - why you don't yourself do what edit you want to do? – user93353 Jul 19 '13 at 09:38
  • @user93353 :) :) ..... – Grijesh Chauhan Jul 19 '13 at 09:40
  • "In my opinion, sounds not so "graceful"..." Why? What is it that you don't like about it? Apart from using different function names, I don't know how this could be improve - without taking a wider look at your design. – Daniel Daranas Jul 19 '13 at 09:58
  • Well, now that we're at it, you can just delete the reference version altogether and just call your pointer version with the address of the reference, i.e. setElem(&refVal) in your calling code. – Daniel Daranas Jul 19 '13 at 09:59
  • 1
    In any case, this code is not RAII-compliant so you absolutely need to document who owns the pointer. And you'd take advantage of rethinking your design altogether to make it follow RAII. See [What is meant by Resource Acquisition is Initialization (RAII)?](http://stackoverflow.com/q/2321511/96780) and [RAII and smart pointers in C++](http://stackoverflow.com/q/395123/96780) for more info. – Daniel Daranas Jul 19 '13 at 09:59

1 Answers1

7
void MyClass::setElem(AnotherClass *pVal)
{
  aclass = pVal;
}

void MyClass::setElem(AnotherClass &refVal)
{
  setElem(&refVal);
}

Is this graceful enough? As Mr. Pitt once said in Seinfeld "Well, you don't want too much grace or you won't be able to stand".

user93353
  • 13,733
  • 8
  • 60
  • 122