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
I have written a program, which takes an input vector of integers and prints all possible permutations of these integers.
In order to do that my program has two methods:
void Permutate(//input) and void DoPermute(//necessary arguments)
Only the method Permutate should be called by the user/client. DoPermutate is a recursive method which is firstly called by Permutate and provides the logic for the algorithm.
The question now: would you put Permutate and DoPermutate in a class and make DoPermutate private, or would you put both methods in the global scope and not use classes at all and thus expose DoPermutate to the user/client? I am asking this because cmath also has the utility methods in a global scope.
What would be a more elegant approach?
The question now: would you put Permutate and DoPermutate in a class
This is what I would to:
Declare Permutate in a namespace, such as:
namespace MyApp
{
// Declare
void Permutate( ... ); // Add all the necessary arguments,
// which can be input arguments ad
// output arguments.
}
Please note that the declaration does not expose whether a class is used in the implementation. That is detail of the implementation that does not need to be exposed in the interface.
If it is helpful to use a class in the implementation, use it.
namespace MyApp
{
// Helper class
struct PermutateClass { ... };
// Implement the user facing function.
void Permutate ( ... )
{
// Delegate the implementation to the helper class.
PermuateClass p(...);
p.doIt();
}
}
If it is not helpful to use a class, just use helper functions as needed.
namespace MyApp
{
// Helper function
void DoPermutate ( ... ) { ... }
// Implement the user facing function.
void Permutate ( ... )
{
// Delegate the implementation to the helper function.
DoPermutate p(...);
}
}
The key point I want to emphasize is that whether you use a helper class with a bunch of member functions or a bunch of non-member function is an implementation detail that you should be able choose without impacting the users of the user facing function.
Related
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());
}
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.
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 6 years ago.
Improve this question
I have a myVector class:
class myVector {
public:
void populateVector();
void showMenu(vector <myVector> const &vec_first);
private:
vector <myVector> &vec_first;
}
I haven't filled my vector yet but I want to essentially use the vector in the showMenu() function, however, a problem arises in my main when I attempt to call the showMenu() function.
int main() {
myVector obj;
obj.showMenu(vector <myVector> const &vec_first);
}
Codeblocks keeps saying:
main.cpp|33|error: expected primary-expression before 'const'
Your are confusing the function declaration with calling it. You need
int main() {
myVector obj;
vector<myVector> vec;
obj.showMenu(vec);
}
or something like that
I haven't filled my vector yet but I want to essentially use the vector in the showMenu() function, however, a problem arises in my main when I attempt to call the showMenu() function.
Don't pass the vector (or anything) in through showMenu; it already has access to the vector, which is a member of the same class.
If you did want to pass a function argument, repeating the argument's original declaration would not be the way to do it. Only its name should be specified. Here that would be:
obj.showMenu(obj.vec_first);
… if vec_first weren't private.
It looks like you need to go back to basics and read the initial chapters of your C++ book.
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 8 years ago.
Improve this question
Just some background:
I am making a monopoly game and now I have to implement the actions of each space such as GO, properties (upgrading), chance, community chest, jail, etc.
I've considered making a different class for each space (but obviously that would be very time consuming). I believe there is also a way do to it with inheritance and pure virtual functions. Any way you guys can think that would make this a simpler process?
Thanks!
There are only a few different types of spaces:
properties
railroads
chance / community chest
utilities
other single ones like go, jail, parking, tax
For example you could have a Property class where each instance of the class has a different name/colour/price. You wouldn't have to make 22 different classes, just have 22 instances of the same class with different names.
Note that having class instances that represent spaces you can land on is only one way to implement a game like that. I'm pretty sure I wouldn't choose that option.
There are two ways you can make a function do different things given an object:
Differentiate the behavior based on the data of the object.
You could capture the differences in the various spaces using data.
enum SpaceType
{
GO, CHANCE, COMMUNITY_CHEST, // etc...
};
class Space
{
public:
void foo()
{
switch (spaceType)
{
case GO:
// DO stuff for GO
break;
case CHANCE:
// DO stuff for CHANCE
break;
// etc..
}
}
private:
SpaceType spaceType;
}
Differentiate the behavior based on the type of an object.
class Space
{
public:
virtual void foo() = 0;
};
class GoSpace : public Space
{
public:
virtual void foo()
{
// Do stuff for GO
}
};
class ChanceSpace : public Space
{
public:
virtual void foo()
{
// Do stuff for CHANCE
}
};
// Similarly for other classes.
Pick your method. Personally, I would pick the second method because the logic for each different type is put into their own functions, without the complications of what other types do.
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 8 years ago.
Improve this question
I'm writing a physics engine in C++ and I've come to a stop, namely how I should design the class hierarchy. What I'm specifically concerned about is the World and Body classes. Body should expose some details to World that World then can work on. But at the same time, I don't want users to be able to access all of those properties of Body. But I still want users of the engine to be able to change some things in a body. For example, its position. How would you structure this in terms of classes?
Define an interface (i.e. a pure virtual class) that specifies what functions you want exposed from Body. Have Body implement that inteface.
Allow that interface, and not Body to be used from World.
This pattern is called composition.
Recently, I've solved a similar problem by introducing a special interface for the restricted operations, and inheriting protectedly from it. Like this:
struct RestrictedBodyFunctions
{
virtual void step() = 0;
virtual Body& asBody() = 0;
};
struct Body : protected RestrictedBodyFunctions
{
static std::unique_ptr<Body> createInWord(World &world)
{
auto Body = std::unique_ptr<Body>{new Body()};
world.addBody(*body); // cast happens inside Body, it's accessible
return std::move(body);
}
std::string getName() const;
void setName(std::string name);
protected:
void step() override
{ /*code here*/ }
Body& asBody() override
{ return *this; }
};
struct World
{
void addBody(RestrictedBodyFunctions &body)
{
m_bodies.push_back(&body);
}
void step()
{
for (auto *b : m_bodies)
{
myLog << "Stepping << " b->asBody().getName() << '\n';
b->step();
}
}
private:
std::vector<RestrictedBodyFunctions*> m_bodies;
};
That way, users can create Body objects using createInWorld, but they only get a handle to (the public part of) Body, while the World gets its handle to RestrictedBodyFunctions.
Another option you have is to reverse the above idea - provide a restricted public interface PublicBody, and have Body derive from PublicBody. Your internal classes will use the full Body, while factory functions make sure only PublicBody-typed handles are available to the clients. This alternative is a more simple design, but provides less control over who can access the full functionality.