is there a way to let the constructor of the object know its name?
I would like to have string myObject.name created by the constructor based on the actual name of the object. Is it possible?
myClass Example;
//constructor creates an object with this name and i would like to have Example.name=="Example";
Thank you for your help!
There's no guarantee that it actually has a source name of any kind, so there's no sense in such a mechanism. And furthermore, tying your user display to the internal implementation details of your source code is a tremendously bad idea.
You, of course, can assign it whatever name you like that you think has whatever meaning you like.
There is no such inbuilt functionality.
Although you can build one for yourself, following is the one way how you can achieve it.
class myClass {
std::string m_objectName;
public:
myClass(std::string name):m_objectName(name);
std::string name()
{
return m_objectName;
}
};
Now create object like this:
myClass Example("Example");
Not very useful, but with a macro you can achieve something near:
#define CREATE( a, b ) a b(b)
int main()
{
CREATE( myClass, example );
}
assuming of course that myClass has a constructor with a string as argument.
On the bottom line, I agree with the other answer, there really no point doing this.
Related
Disclaimer: I'm fairly new to programming and my terminology may be way off. When I say "class pointer name", I mean the "A" in "myClass A" and in "A.Fill(...)".
I'm not sure how to formulate my question to make it as clear as possible, but let me try:
class myClass{
public:
// stuff
Fill(string msg)
{
// does stuff
cout << msg + "some extra text"; /*here I want to somehow get the name of the class pointer
which was used when calling this method, rather than having to manually pass it on as a string.*/
// more stuff
}
};
int main()
{
myClass A;
myClass B;
myClass C;
A.Fill("A");
B.Fill("B");
C.Fill("C");
}
This code is currently doing exactly what I want. However, I am wondering if it's possible to somehow get the class pointer name from within the method, rather than having to manually pass on a string argument every time?
I know that in macros I can use #A #B #C to get exactly that, but I'm uncertain how this would be applied for my code, and if it's possible at all.
You don’t want variable names, and you don’t want to be passing them in each time you call a method of the object.
You want object names. You need to give the A object a name, and then this name can be used by all of its methods.
Then, if you want convenience, instead of instantiating it as ClassA A("A");, you can have a macro that does it, like
#define ClassA_instance(var) ClassA var(#var)
Use:
ClassA_instance(A);
This way, you create an instance of that class that has the same name as the variable - but that’s pure convenience. You will find, soon enough, that you can give objects better names than what suffices for a variable name, especially if those objects are stored inside of other objects, where member variable names may be unwieldy due to eg. the m_ prefix. You can then also combine object names, so that object B inside of some object A will have its name set to “A.B” or similar. Tying the name to the name of a variable will have very limited uses.
ClassA has to store its name of course, and its constructor must accept the name. Eg.:
ClassA {
std::string m_objectName;
public:
ClassA(const std::string &name) : m_name(name) {}
ClassA(const char *name) : m_name(name) {}
...
};
You could factor out the naming aspect into a base class, although there’s so little code to it that I don’t see the sense in doing it - not unless you have other, better reasons to have a common base class.
Not even the compiler knows what variable name was used to call a member function. But you're right, you can use a macro to do what you want.
#define FILL(X) X.Fill(#X)
FILL(A);
FILL(B);
FILL(C);
No, there isn't a way to get a variable name automatically from with a class's function.
To do what you're asking for, it would have to be passed in.
Fill(string name, string msg)
{
//...
}
Perhaps you could come up with a macro that could be used in places where the function call is made that would streamline passing in the name.
myClass A;
CALLFUNCTIONANDPASSNAME(A, Fill("A"));
But in my option that just adds complexity for little value.
Furthermore there are lots of situation where trying to determine the variable name is going to be surprising or unhelpful. For instance:
myClass* p = new myClass[2];
p->Fill("...");
++p;
p->Fill("...");
Here Fill is called on two different instances, but the name of both would be "p". (Disregard the fact that this example does not show good memory management practices. I'm keeping it simple to only show what's relevant to this question.)
The better recommendation for class instances to have a name is to treat that as any other data you want a class to have - carry it in a member variable.
class myClass
{
string Name;
public:
myClass(string name)
{
Name = name;
}
void DoSomething()
{
cout << "My name is " << Name;
}
}
And then construct your instances with the desired name.
myClass fred("Fred");
I want to write a utility in my program which can convert a string to int. I know that I could use atoi or strtol for it but I need some error handling on it. Which is the better way to do it? Should I create a simple global function, maybe only in a specific namespace, or create a class that have a member which can do it for me?
For eg.:
namespace utility{
int ConvertStrToInt(std::string* str, int& convertednum)
{
//do the conversion and error handling
return convertednum;
}
}
or
class Utility{
public:
static int ConvertStrToInt(std::string* str, int& convertednum)
{//do the conversion and error handling here}
}
Sorry if the question sounds a bit silly but I am in a team with 2 other guy and we think about this very differently. 1 says the class is for everything and make classes for everything, and I think that for such a simple problem a simple function is a good solution.
So which is the more efficient? When should I use a simple function and when is the point from where class is the good solution?
Thx for everyone!
The class Utility as you have written it down above somehow contradicts the idea behind object oriented programming, as the method neither uses nor depends on any members of the class. Classes should rather be objects that have certain properties and methods on these properties.
If it is useful to have state in your conversion, use a class. Preferably, a functor so you can pass an instance around as a callable entity. If there is no state, then use a function.
As an aside, your signature and return type should probably look like this:
int ConvertStrToInt(const std::string& str);
Edit concerning this particular example, the C++ standard library provides this functionality already, so you don't need to re-implement it.
namespace is the usual way to go about this.
The function in the class should be declared static anyway, and having a class just so you can group functions together isn't good practice.
Neither. Go for a function object (sometimes called a Functor).
struct str_to_int {
int operator()(const std::string& s) const { return 23; }
};
Why? This gives you the ability to add state if you need it. It works
with all standard algorithm facilities and every modern C++
library. You can make it a template function without your users every
noticing it.
Now you can do things like:
std::vector<std::string> strings;
std::vector<int> integers;
std::transform(begin(strings), end(strings),
std::back_inserter(integers), str_to_int());
Or someday turn your definition into:
struct str_to_int {
int operator()(const std::string& s) const { return 23; }
// ha
int operator()(const std::wstring& s) const { return 42; }
// haha!
int operator()(const char* x) const { return 42; }
};
and the above code will continue to work without a problem. This wont be the case for a free function.
Random Remark: Why would you pass a pointer to a string for
something like that?
I would normally just use a function. Putting it into a class is just
noise (or pseudo-OO, since the class doesn't have any real behavior on
its own).
There is one exception: functional template arguments to the STL are
generally more efficient if you use a class with an operator()(),
rather than a function. (If you use a functional object, the actual
function being called is a compile time constant, and can easily be
inlined. If you use a function, the template argument is the type of
the function, not the function itself, and inlining is less likely.)
Even in this case, however, I'd start with the function, and add the
functional object type if needed.
I have a lib.h, lib.cpp and test.cpp. I would like to ask what is better?
lib.h
class c
{
std::string name;
}*cc;
lib.cpp
{
std::cout << "the name is:" << name << std:: endl;
}
test.cpp
main()
{
c tst;
tst.name="diana";
}
What should I use? std::string name or std::string *name? How can i work with &name, how will my code change and which one of these 2 methods is the best one?
First, I hardly believe your code will compile while in your main you try to get access to private data member name.
About &. It is really hard to define where to start. In short std::string &name is called reference to object of type std::string. Reference is somehow an alias to some other object. The main feature is, that you always have to initialize refence to object while creating and you can't reinitialize reference to point to another object. More about this feature you can read in C++ FAQ
EDIT
Generally you can declare public, protected and private members of your class in with arbitrary ordering:
class MyClass {
//here goes private members when working with class
//and public when working with structs
public:
//here goes public members
protected:
//here goes protected
private:
//here goes private
public:
//here goes public again
};
Ordering of members declaration is actually code policy question. For example, google style guide recommends to put all public members before private.
About hiding function members (not necessary private). You actually can't hide function member declaration, but there are several ways to "hide" implementation, but I am not sure that it's the definition of hiding you are talking about. But you can check PImpl idiom. This requires understanding of pointers so I advice you to start with them first.
Small code sample for working with pointer to string:
#include <iostream>
#include <string>
class MyClass {
public:
std::string *pstr;
};
int main() {
std::string str("test");
MyClass myObj;
myObj.pstr = &str;
std::cout << myObj.pstr->c_str() << std::endl;
}
std::string & name; is a reference. You'll need to initialize it in the constructor, so it actually refers to something. What it refers to must exist as long as your c instance exists. It's not the right solution for this.
std::string name; is an actual variable, use this.
std::string &name is "only" a reference to a string (a bit like a pointer). Because the name definitely belongs to the class c, I think it would make sense to have an instance there.
References are put to good use when passing instances around (to avoid copying).
const std::string&
is reference to a std::string, it is very important to understand the implications of that with respect to the lifetime of variables. Once the referenced variable goes away, the reference is no longer valid, and this is a very common way to f*ck up for beginning C++ programmers.
YMMV, Pick up a good tutorial first, and meanwhile, don't use references unless you know why and what you're doing
Good luck
I'd use: string name; because string* name is just a pointer that needs to be given a value, and then I'd have to think of a way to clean it up later all by myself, and string& name, would be just a name that again has to be initialized.
I have some class, and in it I want to create object of another class ...
Usually I do it in header file, I just put something like:
QString RSSName;
and it works because that class has constructor that has no parameters ...
So here's my problem: how do I do that for some class(let's say ErrorOutput) that has only constructor with 1 or more parameters? I don't want to create pointer to object, I need it to be something like this:
ErrorOutput err("test");
I hope I've described the question correctly, it's little sleepy over here :P
Thanks for help :)
It's a bit hard to tell from your description what exactly you are asking for, but it sounds like "RSSName" is a member variable in your class. If I'm correct about that, initialize it in the constructor's initialization list.
class Foo
{
public:
Foo() : RSSName(someVal) { }
private:
QString RSSName;
}
If I have a base class:
class Base
{
public:
virtual void Test()=0;
};
and, in a dynamically loaded module (.so/.dll), I implemented a class derived from this:
class SomethingFromBase : Base
{
...
};
and, the user, once this library is loaded, asks to create an instance of SomethingFromBase (let's say we get the name from cin.), and, we have no knowledge of SomethingFromBase (i.e, no way to just do if(inputstr == "SomethingFrombase") { ... } is there any way to create an instance of SomethingFromBase?
I'm fairly certain this is impossible in (standard) C++, but, I'm always hoping SO will surprise me!
If this is possible with the addition of some library, I'd still like to know about it.
Thanks!
Edit: See cdhowie's answer. Guides to implementing this technique:
http://www.linuxjournal.com/article/3687?page=0,1
http://www.abstraction.net/ViewArticle.aspx?articleID=67
You typically achieve this by required that plugin libraries define some global variable of a struct type that contains pointers to various functions you can call. (Like setup, teardown, etc.) During the setup function, they would call back into your application to some "register" function where they could pass in a string representing the name of the class, and a factory function pointer that will create an instance when executed.
You stash this away in some map, and when the user enters a string, you look at the map to see if there is a factory function registered. If so, just call it.
So this is not "true" reflection, but you can manually hack it to some degree. See, for example, Pidgin, which allows the specification of protocol plugins that may supply many entries in the protocol list.
EDIT: Here is a nifty guide to implementing something similar. I'm more of a C person, so I can't vouch for it being truly awesome or anything, but at first glance it looks good. I've done similar stuff in C on Linux, and the basic approach works pretty well.
Have a map store the objects of the class, keyed by the class name.
All the classes that need to be created this way, need to be derived from some base class named something like "Creatable"
The code to add the object of the class need to be given with the implementation of class.
//Creatable.h
#define IMPLEMENT_CREATABLE( ClassName ) \
ObjectMap::Instance().Add( string(ClassName), new ClassName );
//ObjectMap.h. This is a singleton
class ObjectMap
{
...........
map<string, Creatable *> myMap;
...........
public:
void Add( const string &className, Creatable * );
Creatable * Get( const string &className );
};
//My Class.h
class MyClass : public Creatable
{
................
};
//My Class.cpp
IMPLEMENT_CREATABLE(MyClass);
//Client.cpp
string className;
cin>>className;
Creatable *anObject = ObjectMap::Instance().Get( className );