Using a global function inside a class - c++

I'm trying to study by myself the OOP and I wanted to know if what I am doing is correct or if it is an anti-pattern. Is it OK to use a global function inside a class? for example:
bool isMale(char s)
{
if(s=='m')return true;
else return false;
}
class person
{
string name; char sex;
bool collocate()
{
if(isMale(sex))cout<<"He's a male!";
else cout<<"She's not!";
}
}
I know this is a very stupid code but I was just trying to explain myself. Is it indicated to use global function inside a class or is it a bad-habit? Should I use other ways or is it OK?
Thanks.

You can do it, yes, and it is not considered an anti-pattern. It is quite often an elegant solution as well.
It is also usually a good idea to wrap your global functions into a namespace

There's nothing wrong with using global functions in C++; the language is a superset of C and global functions are C's bread and butter. A benefit of using a global function is that it doesn't rely on an object being instantiated before the function can be called. This can make the function far easier to test in isolation.
Generally when writing code in this fashion I put my functions into a class and make them static, though. This negates the possibility of writing a function with the same name as some standard library function since it's in a different namespace. i.e:
class Person
{
public:
static bool isMale( char gender )
{
return gender == 'm';
}
bool collocate()
{
if( isMale( m_sex ) )
cout << "He's a male!" << endl;
else
cout << "She's not!" << endl;
}
private:
/// m/f
char m_sex;
/// Person Name
String m_name;
};

Since this method seems to be intimately related to person class, it can be a static method of the class. If you can imagine needing the function without having person class included, and decide that the same function should indeed be used both for person class objects and for everything else, then a global function in a suitable namespace is better. If the method is used by many related classes, but does not seem to belong to any class, then the classes and these helper functions should be neatly in the same namespace.
class person
{
private:
string name;
char sex;
public:
static bool isMale(char s)
{
if(s=='m')return true;
else return false;
}
bool collocate()
{
if(isMale(sex))cout<<"He's a male!";
else cout<<"She's not!";
}
}

You can do it. Yes. Not everything is an object in C++.

This is ok (although isMale needs an argument). ^^
In fact, only functions that really need access to the representation of a class should be memberfunctions. That way, you have fewer functions to worry about if you change your class-representation while keeping its interface.

Related

Declaring a reference to a namespace at runtime in c++

I have a c++ program in which I:
Have a class which contains, as members, function handles, say void (*foo) and void (*bar)
Have a collection of namespaces, each defining functions of the same name, e.g.:
namespace1 contains functions void foo() and void bar()
namespace2 also contains functions void foo() and void bar()
At run-time, I would like the user to be able to pass a variable, say choice, which indicates the chosen namespace. The functions in the class would then be mapped to the corresponding functions in the appropriate namespace.
Currently, I'm using something along the following lines:
if (choice == "namespace1") {
my_class.foo = &(namespace1::foo);
my_class.bar = &(namespace1::bar);
} else if (choice == "namespace2") {
my_class.foo = &(namespace2::foo);
my_class.bar = &(namespace2::bar);
}
This works well, but becomes rather cumbersome when my list of available namespaces increases and given that each namespace provides 9 functions that I would like to pass into the class.
Are there ways that I can tidy this up? My first thought was something like:
if (choice == "namespace1") {
my_namespace = namespace1;
} else if (choice == "namespace2") {
my_namespace = namespace2;
}
my_class.foo = &(my_namespace::foo);
my_class.bar = &(my_namespace::bar);
But, if I understand correctly, I cannot use namespaces as variables.
Is there a better way to formulate this? As structured, is this poor style and, is there a more standard way to go about this?
Thank you for any insights that you might have!
You should be aware of the phases of compilation, at least approximately. Names simply do not exist at runtime. Your existing code works by creating pointers for each and every name within each namespace.
The standard solution is to define an interface.
class IFooBar {
virtual void foo() = 0;
virtual void bar() = 0;
// Other 7 functions.
};
This allows each namespace to define one class instead of 9 functions.
Chances are that the compiler behind the scenes creates a "vtable", an array of function pointers, to implement this interface. This would be approximately the same as you do now, but then automated and without the chance of copy-paste errors.
I suggest using traits.
template<Context C>
struct context;
template<NAMESPACE_1> struct context<> {
static foo_return_t foo(...) {
return namespace1::foo (...);
}
static bar_return_t bar(...) {
return namespace1::bar (...);
}
};
template<NAMESPACE_2> struct context<> {
static foo_return_t foo(...) {
return namespace2::foo (...);
}
static bar_return_t bar(...) {
return namespace2::bar (...);
}
};
Then use like so:
foo_ret_t a;
bar_ret_t b;
if (choice == "namespace1") {
a = context<NAMESPACE_1>::foo(...);
b = context<NAMESPACE_1>::bar(...);
} else if (choice == "namespace1") {
a = context<NAMESPACE_2>::foo(...);
b = context<NAMESPACE_2>::bar(...);
}
Your problem is that the stuff is evaluated at runtime.
To expand on the the answer by #MSalters ...
There is a design pattern that addresses this situation. It is called the Dependency Injection Pattern.
Your class (where you are trying to store foo and bar) is the client.
The namespaces contain classes that implement the interface.
A dependency injector will need to inject the dependency (a pointer to one of the concrete classes in the namespaces) into the client.

Static member has different values

Update: I think I was able to narrow down the problem, see here for a new question that is hopefully more precise.
Update 2: I was able to solve the problem, see the link above :-)
I am trying to understand whether I got something fundamentally confused about how static member variables work.
I have a class (Lets call it cProvider) that contains static member variables (e.g. a pointer) and get/set methods. This class is included by two other classes, let's call them "cWriter" and "cReader", and both instantiate it. cWriter only accesses the setter methods, cReader accesses the getter methods.
My problem is that seem to be multiple instances of the static variables, meaning that when I access a static variable of cProvider through cWriter, it accesses a different physical location than when I access the same variable through cReader.
Is this something that is to be expected? I am doing this in a rather complex and probably unknown framework, ADTF. It might well be that the framework is responsible for this behavior. I checked the process IDs, and cWriter and cReader have the same process ID.
What could be the reason that they still access different addresses? I never had a formal programming education, so I might be missing something fundamental about how static variables work. I am happy for any hints about what could be the problem!
Edit: Condensed version of my code: (To show the gist)
OdometryHistoryWriter.h:
class cOdometryHistoryWriter
{
static bool something;
}
OdometryHistoryWriter.cpp:
bool cOdometryHistoryWriter::something;
OdometryHistoryProviderInputFilter.h:
#include OdometryHistoryWriter.h
class cOdometryHistoryProviderInputFilter
{
cOdometryHistoryWriter m_odoHistWriter;
void setSomething(boolvar);
}
OdometryHistoryProviderInputFilter.cpp:
#include OdometryHistoryProviderInputFilter.h
void OdometryHistoryProviderInputFilter::setSomething(boolvar)
{
m_odoHistWriter.something = boolvar;
return;
}
OdometryHistoryProvider.h:
class cOdometryHistoryProvider
{
bool getSomething();
cOdometryHistoryWriter m_odoHistAcessor;
}
OdometryHistoryProvider.cpp:
bool cOdometryHistoryProvider::getSomething()
{ return m_odoHistAcessor.something;}
Not really an answer, but it's far too long to make a comment, and code in comments is hopeless to read even when it fits [unless it's really short]
I just did this based on your code:
#include <iostream>
class cOdometryHistoryWriter
{
public:
static bool something;
};
bool cOdometryHistoryWriter::something = false;
class cOdometryHistoryProviderInputFilter
{
public:
cOdometryHistoryWriter m_odoHistWriter;
void setSomething(bool b) { m_odoHistWriter.something = b; }
};
class cOdometryHistoryProvider
{
public:
bool getSomething() { return m_odoHistAcessor.something; }
cOdometryHistoryWriter m_odoHistAcessor;
};
int main()
{
cOdometryHistoryProvider a;
cOdometryHistoryProviderInputFilter b;
b.setSomething(true);
std::cout << "Expect true:" << a.getSomething() << std::endl;
b.setSomething(false);
std::cout << "Expect False:" << a.getSomething() << std::endl;
}
and it outputs:
Expect true:1
Expect False:0
as you'd expect (at least I do).
As long as you only have ONE definition of bool cOdometryHistoryWriter::something = false;, it should only ever have one address, and be accessible as one and the same everywhere. If this is not happening, the there's SOMETHING different between your ACTUAL code and the code you posted (not that unusual, I expect more than half of the questions I look at are missing "the code that actually make it go wrong" [inclusive cases of "no code posted"])

OO Design -- where to put non-member functions

I have a class with a complex construction process with many parameters. Multiple clients share objects of this class, and the union of these clients parameters are used to instantiate the class. Therefore I have a factory class that stores these requirements, checks consistency of the various clients' requests, and instantiates the class.
Additionally, there are a common set of use models (or sets of parameters) which multiple clients use for multiple factories.
For instance, consider an example. (Note that the actual code is C++, but my experience is in Python so I'll pseudo-code in Python. Yes, I know that this example wouldn't actually work as-is.)
class Classroom:
def __init__(self, room_size=None, n_desks=None, n_boards=None,
n_books=None, has_globe=False, ... ):
...
class ClassroomFactory:
def __init__(self):
self._requirements = dict()
def addRequirement(self, name, value):
if name.startswith("n_"):
self._requirements[name] = max(value, self._requirements.get(name, 0))
...
def createClassroom(self):
return Classroom(**self._requirements)
# instantiate the factory
factory = ClassroomFactory()
# "client 1" is a geography teaacher
factory.addRequirement("n_desks", 10)
factory.addRequirement("n_boards", 1)
factory.addRequirement("has_globe", True)
# "client 2" is a math teacher
factory.addRequirement("n_desks", 10)
factory.addRequirement("n_boards", 1)
# "client 3" is a after-school day-care
factory.addRequirement("room_size", (20,20))
factory.addRequirement("has_carpet", True)
room = factory.createClassroom()
The common use model is as a teacher, we need 10 desks and a board. I think this is best served by a non-member function/decorator, something like:
def makeTeacherRoom(factory):
factory.addRequirement("n_desks", 10)
factory.addRequirement("n_boards", 1)
return factory
This seems like a great example of the "prefer non-member/non-friend to member" paradigm.
The thing that I'm struggling with is, within the framework of a much bigger OO code, where should these types of non-member functions/decorators live, both in terms of namespace and in terms of actual file?
Should they live in the factory's file/namespace? They are closely related to the factory, but they're limitations on the general factory, and need not be used to use the factory.
Should they live in the client's file/namespace? The client understands these use models, but this would limit re-use amongst multiple clients.
Should they live with a common base class of the clients (for instance, one could imagine a "teacher" class/namespace which would also provide the non-member function makeTeacherRoom(), which would be inherited by MathTeacher and GeographyTeacher.
Should they live somewhere else completely, in a "utils" file? And if so in which namespace?
This is primarily a personal decision. Most of your options have no technical negative effects. For example:
They could, because of locality of use, but it's not necessary.
They could, because of locality of data, but again...
They could, although this one does seem like it could make things a bit messier. Making utility classes, you may have to end up inheriting them, or making parts virtual to override later, which will get ugly pretty quick.
This is my personal favorite, or a variant of this.
I typically make a relevantly-named util file (or class with static methods) and put it in the same namespace as the classes it utilates (the more helpful version of mutilate). For a Education::Teacher class, you could have a Education::TeacherUtils file or class containing the functions that operate on Teacher. This keeps a pretty obvious naming tie-in, but also puts the util functions in their own area, so they can be included from whatever needs them (in the Teacher.cpp or similar would prevent that). In the case of a class, you can make the util and base classes friends, which is occasionally helpful (but something to use rarely, as it may be a smell).
I've seen a naming variation, Education::Utils::Teacher, but that's somewhat harder to translate to files (unless you put things into a utils dir) and can also cause name resolution oddness (in some contexts, the compiler may try to use Education::Utils::Teacher instead of Education::Teacher when you didn't mean to). Because of this, I prefer to keep utils as a suffix.
You may want to handle non-member functions in a singleton class for your application. A factory maybe executed from the program, or another object.
C++ supports global functions (non member functions), but, using a single object for the application, "does the trick".
Additionally, since the "Classroom" object may be instantiated with many optional parameters, you may want to assign it, after calling the constructor ( "init" in python ).
// filename: "classrooms.cpp"
class ClassroomClass
{
protected:
int _Room_Size;
int _N_Desks;
int _N_Boards;
int _N_Books;
bool _Has_Globe;
public:
// constructor without parameters,
// but, can be declared with them
ClassroomClass()
{
_Room_Size = 0;
_N_Desks = 0;
_N_Boards = 0;
_N_Books = 0;
_Has_Globe = false;
} // ClassroomClass()
public int get_Room_Size()
{
return _Room_Size;
}
public void set_Room_Size(int Value)
{
_Room_Size = Value;
}
// other "getters" & "setters" functions
// ...
} // class ClassroomClass
class ClassroomFactoryClass
{
public:
void addRequirement(char[] AKey, char[] AValue);
} // class ClassroomFactoryClass
class MyProgramClass
{
public:
ClassroomFactoryClass Factory;
public:
void makeTeacherRoom();
void doSomething();
} // class MyProgramClass
void MyProgramClass::addRequirement(char[] AKey, char[] AValue)
{
...
} // void MyProgramClass::addRequirement(...)
void MyProgramClass::makeTeacherRoom()
{
Factory.addRequirement("n_desks", "10")
Factory.addRequirement("n_boards", "1")
} // void MyProgramClass::makeTeacherRoom(...)
void MyProgramClass::doSomething()
{
...
} // void MyProgramClass::doSomething(...)
int main(char[][] args)
{
MyProgramClass MyProgram = new MyProgramClass();
MyProgram->doSomething();
delete MyProgram();
return 0;
} // main(...)
Cheers
Personally I would make them static members of the class.
class File
{
public:
static bool load( File & file, std::string const & fileName );
private:
std::vector< char > data;
};
int main( void )
{
std::string fileName = "foo.txt";
File myFile;
File::load( myFile, fileName );
}
With static methods they have access to the private data of the class while not belonging to a specific instance of the class. It also means the methods aren't separated from the data they act on, as would be the case if you put them in a utility header somewhere.

Class and Member Function (beginner)

I'm currently reading a c++ book, and I have a few questions.
1) Is void only used to declare a return type in this example?
2) If void causes it NOT to return data to the calling function, why is it still displaying the message "Welcome to the Grade Book!"?
3) Isn't it easier to create a simple function instead of making an object?
#include <iostream>
using namespace std;
class GradeBook
{
public:
void displayMessage()
{
cout << "Welcome to the Grade Book!" << endl;
}
};
int main()
{
GradeBook myGradeBook;
myGradeBook.displayMessage();
}
That's the only use in this example. You can also have pointers to void (void *).
You're not returning that message. You're printing it. In C++, methods and functions can have side effects. One possible side effect is output.
Yes, in this case. However, this is not a realistic example of the benefits of objects. For that, see How do I describe Object-Oriented Programing to a beginner? Is there a good real-world analogy? among many places.
Is void only used to declare a return type in this example?
Yes, it indicates that displayMessage() will not return back anything to it's caller.
It can also be used as a void *, i.e: A generic pointer which can point to anything, but it is not being used in that way in your example.
If void causes it NOT to return data to the calling function, why is it still displaying the message "Welcome to the Grade Book!"?
The message is not returned to the caller of the function, the message is directed to the standard output when the control was in the function and executing that particular statement.
Isn't it easier to create a simple function instead of making an object?
It's not a matter of ease. It is more of an matter of Object Oriented design principles.
The purpose of having classes and member functions is to bind together the data and the methods that operate on that data in a single unit. You might want to pick up a good book and read up Encapsulation & Abstraction.
The Definitive C++ Book Guide and List
In your case the function "displayMeassage" is not returning the string, it is just printing your message.
Returning means, suppose an example:
class A
{
int num=0;
int getNum()
{
return num;
}
};
void main()
{
A a;
int no=a.getNum();
cout<<"no : "<<no;
}
In above example, then way getNum is returning the number that is what returning is
called.
Whatever you are taking the example is not good to understand the return concept.
Thanks

find out identifer name and typeid of the object or variable in C++?

I've started learnig C++ (year ago) mostly because it's univerzal language IMO, and beacause almost everything is possible.
but one thing isn't so:
for example we are writing some code inside an object(class) and we need to find out it's name somehow:
class Test
{
public: const char* getMyIdentiferName()
{
// what now??
}
};
well the best option is to use 'this' keywod but that wouldn't help cos 'this' cant return name?
Test thatsMyName;
const char* = thtsMyName.getMyIdentiferName(); //return string "thatsMyName" how?
how do we get 'thatsMyName' string in in some generic function or even template??
ANOTHER EXAMPLE:(please answer this too)
how do we get typeid of some class?
class MyType
{
public: type_info getType()
{
return typeid(this); //that wont work of course :)
{
};
this looks funny but if any of you have some idea on how to achive similar task...
thanks alot.
EDIT: OK, everybodey say it's impossible to get the name of an object, I found out how to get the name:
class Test
{
public: string getObjectName()
{
string arg = typeid(*this).name();
arg.erase(arg.begin(), arg.begin() + 5);
arg.erase(0,1);
return arg;
}
};
int main()
{
Test thisIsMyName;
cout << thisIsMyName.getObjectName() << endl;
cin.ignore();
return 0;
}
EDIT:
Big thanks to Fiktik answering my second example who found the way oon how to get the type_info of the object!
The first thing you are asking is not possible. At least not directly.
You could create a macro for variable declaration that would register its name somewhere, something like this:
#define CREATE_VARIABLE(type, name) registerVariable<type>(#name); type name
but this is quite cumbersome and cannot be used everywhere. Why would you even want to have this functionality?
The second thing should work with only little adjustments:
class MyType
{
public:
const type_info& getType()
{
return typeid(*this);
}
};
What would you need the variable name for? What you're trying to do is impossible; inside an classes' methods, the name of the variable used for accessing an object isn't known.
Consider this example:
Test * myTest = new Test();
Test * myTest2 = myTest;
const char* identifier = myTest2->getMyIdentifierName();
What should getMyIdentifierName() return? "myTest"? "myTest2"? Nothing at all, since the object was allocated dynamically, and therefore no variable can really claim to "hold" the object?
If you just want to know the variable name which you are currently using for referring to an object, why not just use a string literal for it and pass it wherever you need it? But that doesn't seem to make sense in any real-world application.
If you need a name (i.e., a unique identifier) for an object at runtime, you'll best give the class a member name and initialize that with whatever you need.
Getting the "identifier name" of an object won't work, since there is no unique identifier for an object (other than it's address, to be gotten with &). An unlimited number of references/pointers can designate the same object; at the same time, the language allows objects to be reached by other means than identifiers (v[0] where v is a vector is an object, but not an identifier). This is the case in all programming languages that I know, and I know a dozen of them.
As for your second question, you can return a reference to an std::type_info.
struct Test
{
// pretty useless method
std::type_info const &type() const { return typeid(*this); }
};
int main()
{
Test a;
std::cout << a.type().name() << "\n";
}