Public Setters vs. Friend Class vs. Specific Constructor [closed] - c++

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 months ago.
Improve this question
I'm making a simple programming language, and have encountered the following problem:
I have a Parser class which has methods that return derived classes of the Node struct. Currently all of the Parser class methods look something like this:
DerivedNode Parser::ParseDerived()
{
DerivedNode node{};
node.Field1 = 0;
node.Field2 = 10;
return node;
}
I recently switched the Node type from being a struct to a class, because I want to implement some oop, thus I made fields of Node class private. I'm refactoring the Parser class and struggling to decide, what is the best option out of these 3:
// Option 1: Public setters
DerivedNode Parser::ParseDerived()
{
DerivedNode node{};
node.SetField1(0);
node.SetField2(10);
return node;
}
// Option 2: Making Parser a friend of all Node derived classes
DerivedNode Parser::ParseDerived()
{
DerivedNode node{};
node.m_Field1 = 0;
node.m_Field2 = 10;
return node;
}
// Option 3: Storing in variables and calling a constructor
DerivedNode Parser::ParseDerived()
{
size_t field1 = 0;
size_t field2 = 10;
return DerivedNode{ field1, field2 };
}
I would love to hear which of these methods is the best and some arguments why (sorry for my English).

A class is supposed to hold an invariant. Unless all combination of all field values are correct, 2nd version is strongly discouraged; 3rd is recommended. It's also the way to go for immutable structures which help debugging and testing very much.

Related

How to create functions to manipulate objects inside objects with protected or private atributes? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm trying to learn about classes/inheritance(in general), so I'm trying to make a game as a semester final project.
Lets say I have a class SOLDIER with an object of a class INVENTORY with an object of a class POTION (with size and amount).
If I want to make a function use_potion(), how do I do that? I could have everything public to make something like "soldier1.addlife(soldier1->inventory1->potion1->size), but that looks like a terrible practice. How do I do implement that with private/protected atributes?
*The potion is only 1 of the functions I will need to make with the same structure - object->object->object->something -, so I really need some help and examples to understand how to make them.
You need to add a public function in your SOLDIER class that invoke public function in INVENTORY object that invoke public function in POTION obj.
Here is an example structure of your program:
class SOLDIER
{
private:
class INVENTORY
{
private:
class POTION
{
int size = 5;
public:
void use_potion()
{
size++;
printf("use_potion in POTION obj");
}
};
POTION pot;
public:
void use_potion()
{
pot.use_potion();
}
};
INVENTORY inv;
public:
void use_potion()
{
inv.use_potion();
}
};
int main()
{
SOLDIER s;
s.use_potion();
return 0;
}

What is the size of empty derived class in c++ and java? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have got some related answers like Why the size of empty class that is derived from two empty classes is 2? but not get the answer to my question clearly.
interface PI1
{
default void show()
{
System.out.println("Default PI1");
}
}
interface PI2
{
default void show()
{
System.out.println("Default PI2");
}
}
class TestClass implements PI1, PI2
{
public void show()
{
PI1.super.show();
PI2.super.show();
}
public static void main(String args[])
{
TestClass d = new TestClass();
d.show();
}
}
Does this JAVA program show multiple inheritance?
In C++ the minimum size is 1.
However, the other question is about multiple inheritance from base classes of the same type. Two objects of the same type cannot have the same address, because then they would not be different objects.
The address is an important part of the identity of an object.
So, if you have two objects of the same type, the minimum size would be 2.
None of this happens in Java, because there is no multiple inheritance.

should a class manage its instantiated objects? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
lets assume I have a number instance of a class vehicle instantiated. if the vehicle object wants to query other existing vehicles for some reason ( for example finding the nearest vehicle), should the class manages the instantiated objects through static members and methods as in the code below? is this a good design pattern? is this a common standard? is there any pitfall if i take this approach?
#include <vector>
#include<algorithm>
struct Location {
double x, y, z;
Location(double xx, double yy, double zz) : x(xx), y(yy), z(zz) {}
};
class Vehicle {
private:
Location l;
public:
Vehicle (Location ll) : l(ll) {
vv.push_back(this);
}
static std::vector<Vehicle*> vv;
~Vehicle() {
std::vector<Vehicle*>::iterator it;
// removing the Vehicle object from the list of existing vehicles
for (it = vv.begin(); it != vv.end(); it++){
if (*it == this) {
vv.erase(std::remove(vv.begin(), vv.end(), this), vv.end());
}
}
}
Vehicle& find_nearest_vehicle () {
// code to iterate through list of existing vehicles and find the nearest vehicle 
}
};
static std::vector<Vehicle*> vv;
Put it into any of the typical OO scenarios used as examples:
Does an animal know about every other animal?
Does a car know about every other car?
Does a color know about every other color?
What you are asking is really opinion based, but I'm sure most people would say "no". You use some kind of manager class to control the instances.
In your case I'd have a Vehicle which knows it's location and a VehicleManager which knows about all the Vehicles. If you want to know what color a Vehicle is you ask the Vehicle. If you want to know where all the Red Vehicles are - you ask the VehicleManager.
Your solution has a combined Vehicle/VehicleManager which relies on a static collection of vehicles so you can only ever have one set. If you use two classes as I've described you can have multiple sets. e.g. Vehicles of different companies or trucks vs cars etc - sure there are other ways to do this as well, but your solution locks you in. Using 2 classes is much more flexible.
So to answer your last comment: do you think it's ok or is it a terrible design? - It is terrible design.

confused about class structure in code [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am reading a sample code that uses C++ and classes, I am new on C++ classes I can work with basics similar to this http://www.cplusplus.com/doc/tutorial/classes/, but I cant understand what the code below does mean or the color it is using visual studio c++
thanks
I am sorry if it is a fool question
It creates an object named some by instantiating the class some.
Then it calls the member function ToVector() on the object some and pass the result of the call to the function named function.
class is blue because it is a keyword of the C++ language.
The first some is green because it is the name of a class.
The second some is black because it is a variable.
And function and ToVector are red because the are functions.
Now this is ugly code because you "hide" the class some by reusing the same name for your variable. Also you do not need to put the word class here.
Here is a more complete and nicer version:
#include <vector>
class Some
{
public:
std::vector<int> ToVector()
{
return std::vector<int>(); //return an empty vector
}
};
int f(std::vector<int> v)
{
return 0;
}
int main(int, char**)
{
Some some; // Was "class some some"
return f(some.ToVector());
}

Using Factory Method pattern for different arguments [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Hello my question is regarding if its possible to use the factory pattern for classes with same number of arguments in their constructor but different types. For example, I have an interface called IVerify. I have 2 classes that implement them, NameVerifier, which takes in a String name in its constructor, and IntegerVerifier, which takes in an int num in its constructor. Is it possible to do the factory pattern in this case?
Could we use IVerify Factory.CreateNameVerifier(string) and IVerify Factory.createIntegerVerifier(int) Is it still considered as a factory pattern?
Additional note: Im using c++
If there are many versions of NameVerifier and IntegerVerifier then your solution is still a Factory Pattern since you will be abstracting which class to instantiate inside CreateNameVerifier and CreateIntegerVerifier.
But if Verifiers are unique w.r.t to the type of Argument that they take i.e., there is only one NameVerifier and only one IntergerVerifier and they differ because of their types then your existing solution is just creating a sort of wrapper to create objects/Verifiers. In such case it should be something like this:
Reference: Factory Pattern
class IVerify
{
};
class CNameVerifier : public IVerify
{
};
class CIntegerVerifier : public IVerify
{
};
class CVerifierFactory
{
enum TYPE
{
STRING,
INTEGER
};
template<typename T>
IVerify* CreateVerifier(const CVerifierFactory::TYPE &_enumType, T _Parameter)
{
IVerify *pVerifier = NULL;
switch(_enumType)
{
case (CVerifierFactory::STRING)
pVerifier = new CNameVerifier(_Parameter);
break;
case (CVerifierFactory::INTEGER)
pVerifier = new CIntegerVerifier(_Parameter);
break;
}
return pVerifier;
}
};
CVerifierFactory g_oFactory;
IVerify *pVerifier = g_oFactory.CreateVerifier(CVerifierFactory::STRING, "Alex");
if(pVerifier != NULL)
{
//use pVerifier
}
Note: Strict Type Checking of arguments _Parameter are not done before creating Verifiers. You can extend the number of arguments for object creation using Variadic Template/Parameter pack.