I have a class Item
that has a non-default constructor and doesn't have a default constructor. There is no default constructor because I don't want to have Item
objects with some strange default values around.
class Item {
int a;
public:
Item(int a) : a(a) {}
}
Another class User
uses Item
class and has a method GetItem(Item * item)
that returns an Item
object by pointer.
class User {
Item item;
public:
bool SetItem(Item item) {
this->item = item;
return true;
}
bool GetItem(Item * item) { // Can't do "Item * GetItem()"
*item = this->item;
return true;
}
}
The problem is when I try to GetItem()
from somewhere in my program, I still need to allocate memory for an Item
object by using some random values, for example Item anotherItem(999);
User user;
Item item(5);
user.SetItem(item);
// Here is the problem
Item anotherItem(999); // any random value
user.GetItem(&anotherItem);
What is the best practice to handle such situations? Is it better to have a default constructor?
Thank you for your help in advance.
2 Answers 2
In a situation like yours, there are only a few real options
- Allow creation of a default-constructed
Item
. This means adding a default constructor - Return a (pointer to a)
Item
fromGetItem
- Take a
Item**
orItem*&
and let the passedItem
pointer refer to the internalItem
ofUser
.
None of the options is inherently better than any of the others, although the third one has the big drawback that it allows modification of User
content without going through a method of the User
class. That opens up the door for violating the constrants that User
tries to uphold.
-
Thank you for your reply! Could you please explain the second option?Konstantin– Konstantin2017年02月16日 09:09:32 +00:00Commented Feb 16, 2017 at 9:09
-
1@Konstantin Second options means changing the
GetItem
method of theUser
class toItem* GetItem() const { return &item; }
. I added theconst
qualifier as a convention because the call does not modify theUser
object.Andy– Andy2017年02月16日 09:11:04 +00:00Commented Feb 16, 2017 at 9:11 -
@Bart van Ingen Schenau Thank you for the clarification.Konstantin– Konstantin2017年02月16日 09:14:14 +00:00Commented Feb 16, 2017 at 9:14
You can use a pointer for the anotherValue Item. You don't have to call the constructor, you can pass it to the getItem function, you don't have to manage it, Because clearly you don't have the ownership of it.
-
1Thank you for the reply, but I'm not sure that I completely understand it.Konstantin– Konstantin2017年02月16日 07:59:27 +00:00Commented Feb 16, 2017 at 7:59
-
You can declare anotherValue that now is a Item as a Item* (Item pointer) in this way you can skip the constructor call.LaboPie– LaboPie2017年02月16日 08:00:52 +00:00Commented Feb 16, 2017 at 8:00
-
Can you provide a code sample, please?Konstantin– Konstantin2017年02月16日 09:05:56 +00:00Commented Feb 16, 2017 at 9:05
Explore related questions
See similar questions with these tags.