This question already has answers here:
What is the 'this' pointer?
(8 answers)
Closed 5 years ago.
so I saw this syntax
this->
used in a c++ tutorial on udemy but it was not explained to me as to what exactly why I would use this in programming. Can anyone provide an example program or proper example code that shows what this does? Please explain the logic behind it. Please don't say Google it. I know it has something to do with pointers and memory. and what not I guess another thing I am looking for is an explanation a five year old would understand or broken down enough for easy comprehension.
this keyword is used to reference current instance of given class, for example:
class A {
public:
void setName(std::string name) {
// if you would use name variable directly it
// will refer to the function parameter,
//hence to refer the field of the class you need to use this
this->name = name;
}
private:
std::string namel
}
Related
This question already has answers here:
Why use a const member function?
(3 answers)
What are the semantics of a const member function?
(9 answers)
Closed 2 months ago.
This post was edited and submitted for review 2 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Edit: From #Jeremy Friesner's answer, he provides another view point that Why use a const member function & semantics of a const member function don't cover. It can improve clarity and disambiguous your code. People can have a brief idea of what this function is supposed to do or not do at the first glance. Very useful especially in working with others.
I come across the constant function lately.
It says:
Constant functions are those have denied permission when attempting
to change the member variables of their classes.
My questions are
In a programmer perspective, if you don't want a function being able to change member
variables, why not just moving the parts responsible for changing variables outside
of the function at the first place? (e.g using another function)
What/when are some practical moments of having the neediness to use a constant
function?
Appreciate any answers
class Foo
{
public:
int x = 0;
int Bar(int arg) const
{
x++; // fails
return x; // okay
}
};
The purpose of const-tagged methods isn't to prevent the programmer from intentionally modifying member variables, but rather to allow the compiler to assist the programmer by producing a compile-time error when the programmer accidentally modifies a member-variable. This is useful because it's much easier and quicker to correct a compile-time error than to chase down a run-time misbehavior through manual testing.
The const tag also assists later programmers who are reading the class's header file by helping them quickly understand what a method does or does not do. For example, if you see this in a class declaration:
class MyClass
{
[...]
int CalculateTheValue();
... you might ask yourself, "does calling CalculateTheValue() change the state of the MyClass object?" With a name like CalculateTheValue() it seems like it shouldn't, but there's no way to know for sure without finding the corresponding .cpp file and reading through the code that implements that method... which is a tedious and error-prone way to do things.
On the other hand, if you see this:
class MyClass
{
[...]
int CalculateTheValue() const;
... then you know right away that CalculateTheValue() will not modify the MyClass object you call it on, because it says so in the declaration. (if it did try to modify the MyClass object, the code wouldn't compile; so if the code compiled, we know it doesn't modify it)
This question already has answers here:
What is this weird colon-member (" : ") syntax in the constructor?
(14 answers)
Closed 5 years ago.
CWmcaIntf::CWmcaIntf() :
m_hDll(NULL),
m_pLoad(NULL), m_pFree(NULL), m_pSetServer(NULL), m_pSetPort(NULL), m_pIsConnected(NULL),
m_pConnect(NULL), m_pDisconnect(NULL), m_pTransact(NULL), m_pQuery(NULL), m_pRequest(NULL), m_pAttach(NULL),
m_pDetach(NULL), m_pDetachWindow(NULL), m_pDetachAll(NULL), m_pSetOption(NULL),
m_pSetAccountIndexPwd(NULL), m_pSetOrderPwd(NULL), m_pSetHashPwd(NULL), m_pSetAccountNoPwd(NULL), m_pSetAccountNoByIndex(NULL)
i dont know what this grammer means. i am trying to use a header file 'CWamInf'. and want to know different methods or problems .. thanks..
I don't know how much you know about headers classes and stuff so I'll try to explain everything I can.
CWmcaIntf::CWmcaIntf() :
The CWmcaIntf:: means that the function that is about to be defined after the double colon is within the class "CWmcaIntf".
The CWmcaIntf() is a constructor : it has the same name as the class and its purpose is to construct each object of a class depending on the code you put in it. I'd say that often, its only purpose is to initialize member variables. If it isn't clear yet, check this link.
m_hDLL(NULL)
As you most certainly know, programmers tend to respect and harmonize on coding conventions. One of those is to name all member variables by m_something, so your code become easier to understand for you and everyone else.
So here, all you got is a constructor initializing a lot of member variables to NULL, which means that when a CWmcaIntf object will be constructed, its member variables will be equal to nothing and only be modifiable with setters if data are properly encapsulated.
Now if the purpose of your question was for us to tell you more about what does mean the member variables, and what the constructor may do, well don't expect an answer since zero details ae given and nothing even matches the tutorial explaining how to properly ask a question.
This question already has answers here:
How can I add reflection to a C++ application?
(28 answers)
Closed 7 years ago.
Is there a way that I could obtain a list or maybe iterate through a list of each member variable of a class -regardless of it's type.
My intention is to add them all to a template std::map.
class Person
{
int Age;
char *Name;
template<typename Container> std::map<char *, Container> List;
void MakeList()
{
for(auto i : Person.memberVariables)
{
List.emplace(i);
}
}
};
Could I do something like the above to add each variable of my class to the list, regardless of how incorrect the other code is. The adding to the list is what I'm interested in.
Thanks in advance.
No, you can't do it in C++. this is called reflection which is currently not supported in C++.
The ISO C++ comitee talks about compile time reflection that is proposed for C++17 that will let you to iterate over class members on compile time. but it will take much time until this feature will be standarized and be implemented on the common compilers
as a side note, I don't see why one would want to iterate over member variables other then maybe implementing serialization method , which in this case I would require the class to implement serialize method and enforce it with SFINAE.
If there is, I would be very surprised.
This is called reflection, and as far as I know this isn't supported by C++.
This question already has answers here:
What are the differences between a pointer variable and a reference variable?
(44 answers)
Closed 7 years ago.
So I have a pointer SparseMatrix *mat which holds values of the sparsematrix in a triplet format from a file. After I get the values, I would like to be able to just print it out using a print function I created in the SparseMatrix() class. However, I realize that this works if it wasn't a pointer and just 'mat'. I feel like this is something simple but I just cannot wrap my head around it. Any suggestions? Forgive me if this is an extremely noob question. Also, the reason I'm even using a pointer in the first place is because I am trying to visualize a sparsematrix using QT and my professor had given the basic backbone of the code. In that code, a private variable, SparseMatrix *mat was given.
Via pointers you can access your functions using ->.
This question already has answers here:
Get attribute by name
(5 answers)
Closed 4 years ago.
In the vein of more impossible-but-is-it-really questions:
Is it possible to access the member variable of a class, where the variable's name is stored in a string?
class Test
{
public:
int test = 0;
}
string name = "test"; // let's assume we know test is an int.
Any chance of getting the value of test, using the string?
One bit of cheating not allowed:
enum vartype {
INT,
..
}
No forcing the class to register all its variables in a std::map<string, std::pair<vartype, void*> >.
All other tricks welcome.
Thanks!
No.
To do this, you need to provide some mapping between member variables and the string names by which you intend to access them.
In the realm of really ugly kluges, you could build the program with debug information and have it use that to find the location of the variable in the same way a debugger would. But other than that, you're out of luck. C++ doesn't do reflection.
About why it's not available in C++ and an alternative: http://en.allexperts.com/q/C-1040/eval-function-javascript-C.htm
It's possible in MATLAB though...
As a very simple example, if you have a matrix updation to do, which goes like:
M1=1;
M2=2;
M3=3;
And you would prefer that the variable names could be altered so that you could use a for loop, then it can also be done this way:
for i=1:3
eval(['M' num2str(i) '=' num2str(i)]);
end
I used to do this in Actionscript. Was really glad to find that it's available in Matlab too