Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
For some reason, I can't seem to get the built-in queue class of C++ to work within a class I create in the way the same built-in queue works in main. I want the queue I use in my class to contain the values of the variables I add to it. But when I use the built-in queue in my class, the queue seems instead to contain something else, maybe addresses of the variables.
What am I doing wrong please?
#include <queue>
#include <iostream>
#include <cstdlib>
using namespace std;
class Myclass {
private:
queue<int> q;
public:
Myclass();
void qPush(int n){ q.push(n); }
int qFront(){ q.front(); }
void qPop(){ q.pop(); }
};
Myclass::Myclass() { // Default Constructor
}
int main () {
int num1 = 0;
int num2 = 1;
queue<int> myQ;
myQ.push(num1);
myQ.push(num2);
cout << myQ.front() << endl;
myQ.pop();
cout << myQ.front() << endl;
cout << "Myclass version: " <<endl;
Myclass b;
b.qPush(num1);
b.qPush(num2);
cout << b.qFront() << endl; // I want this to print out an int. But it looks like it may be printing out an address instead?
b.qPop();
cout << b.qFront() << endl;
return 0;
}
The output I get:
0
1
Myclass version:
537168208
537168212
The problem is that MyClass::qFront() doesn't have a return statement, and because of that it returns a garbage value.
You just need to add the return statement:
int qFront(){ return q.front(); }
To make this code work better you could also add const qualifier to make the method usable with const objects:
int qFront() const { return q.front(); }
Here is an example which demonstrates why it might be necessary:
Myclass a;
a.qPush(42);
const MyClass b = a;
cout << b.qFront(); // This line results in a error if the method isn't marked as const.
The rule here is that you should always mark methods that don't modify object state as const (if you don't have a good reason to do otherwise).
You could also add a second version (overload) of this function which would return a reference to int instead of actual int:
int qFront() const { return q.front(); }
int &qFront() { return q.front(); }
Then the first one would be used for const objects and the second one would be used for mutable ones.
Because it returns a reference to int instead of just a plain int, you could modify the returned value:
Myclass a;
a.qPush(42);
cout << a.qFront();
a.qFront() = 13;
cout << a.qFront();
(Note that compiler wouldn't allow you to write int &qFront() const { return q.front(); }, because it would allow you to modify contents of const objects, which is a bad thing.)
This question already has answers here:
Calling a function pointer whose assigned function has less arguments then the pointer type
(2 answers)
Closed 7 years ago.
take a look at the following example:
#include <iostream>
#include <string.h>
void Func1(int x)
{
std::cout << "I'm function 1: " << x << std::endl;
}
void Func2(int x, const char* str)
{
std::cout << "I'm function 2: (this is arg1: " << x << " - args2: " << str << ")" << std::endl;
}
uintptr_t GetProcAddress(const char* _str)
{
if (strcmp(_str, "func1") == 0)
{
return reinterpret_cast<uintptr_t>(Func1);
}
else
{
return reinterpret_cast<uintptr_t>(Func2);
}
}
int main()
{
typedef void(*PROCADDR)(int, const char*);
PROCADDR ext_addr = nullptr;
ext_addr = (PROCADDR)GetProcAddress((const char*)"func1");
//call the function
ext_addr(10, "arg");
std::cin.get();
return 0;
}
We are basically calling Func1 with 2 arguments and can switch to call Func2 with the same args and everything works as intended.
Of course the address of both the arguments are always pushed on to the stack even though the second one is never used by the function itself.
Now I understand that the above code should never be used in production-code but my main question is, can the above code cause UB or is the code always expected to act like that?
Best regards
xx
Yes, it's undefined behavior. From [expr.reinterpret.cast]:
A function pointer can be explicitly converted to a function pointer of a different type. The effect of calling
a function through a pointer to a function type (8.3.5) that is not the same as the type used in the definition of the function is undefined.
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 8 years ago.
Improve this question
if we create a class like this :
class Sales_data
{
std::string isbn() const {return bookNo;}
std::string bookNo;
};
And we make a object total;
Sales_data total;
total.isbn();
The C++ Primer, fifth edition, says (page 258),"when we call a member function, this is initialized with the address of the object on which the function was invoked "
,it like this:
Sales_data::isbn(&total)
and the book also write,we can get the bookNo like :
std::string isbn()const {return this->bookNo;}
I think the implicit parameter "this" just like a pointer,
but i can't see it type,would anybody help me point what wrong i think and what should i do to understand the implicit parameter 'this' and this parameter works for?
#Jason C
my extra question:
this is a pointer,so it behave like a normal pointer,
#include "iostream"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int a = 1;
int * b = &a;
cout << "the b is " << b << endl;
cout << "the &a is " << &a << endl;
cout << "the *b is " << *b << endl;
cout << "the &b is" << &b << endl;
return 0;
}
on my computer the output is :
the b is 0110FCEC
the &a is 0110FCEC
the *b is 1
the &b is0110FCE0
then ,What's the use of the type of the pointer.
this is not a parameter, it is a way for an object to refer to itself.
If you use visual studio or any modern IDE you can check that this has the same type as the class of which it is a member of.
There is a good book called "The C++ Object Model" by Stanley B. Lippman which can help understand.
Even if not defined as such in the standard, every implementation I am aware of makes this an implicit parameter to a member function and can be viewed as such.
In C++, you do
object->function () ;
In contrast, in Ada the syntax is
function (object) ;
The object is then an explicit parameter to the member function. The this variable is a product of C++'s member calling syntax. Instead of the programmer having to explicitly declare a parameter identifying the object (as in Ada), C++ does this automatically for you (this).
In most implementations, C++ parameters are bound to offsets to locations on the stack or to registers. This is implemented in the very same way as other parameters (either bound to a stack offset or a register).
this is a pointer to whatever instance of an object the member function is being called on (note that there is no this in static member functions or non-member functions, then).
In your case, it is either a Sales_data * or const Sales_data * depending on the context. Inside isbn(), it is the latter.
This (contrived) example illustrates its value:
class Example {
public:
void function (Example *x);
};
void Example::function (Example *x) {
if (x == this)
cout << "x is this!" << endl;
else
cout << "x is not this." << endl;
}
Now if we do:
Example a;
Example *b = new Example();
a.function(&a); // outputs "x is this!"
b->function(b); // outputs "x is this!"
a.function(b); // outputs "x is not this!"
b->function(&a); // outputs "x is not this!"
Also, since it's a pointer to the "current" instance of the object:
class Example2 {
public:
int k;
void function ();
};
void Example2::function () {
k = 42;
this->k = 42; // does the same thing as above!
}
In a logging context, I would like to use a temporary instance of a utility class to collect some output, and use the destructor to dispose of the collected output. For example, printing to standard output as below.
I am noticing behavior differences depending whether the utility instance is constructed as an inline, anonymous instance as compared with a named automatic instance.
The named instances result in expected behavior and output. The inline instances have difficulty with the first insertion operation, apparently only working on operands which have simple conversions to int.
What is the difference between instances used in these different ways?
#include <string>
#include <sstream>
#include <iostream>
class Util
{
public:
std::ostringstream m_os;
Util() {}
~Util() { std::cout << m_os.str() << std::endl;}
};
int main (void)
{
// ----------- Using temporary anonymous instance -
// Output does not match expected, and the first insertion seems to
// only be able to handle instances that can be converted to int.
// Following prints "97key=val", but expect "akey=val"
(Util()).m_os << char('a') << std::string("key") << "=" << std::string("val");
// Following prints "0x80491eakey=val", but expect "Plain old C string key=val"
(Util()).m_os << "Plain old C string " << std::string("key") << "=" << std::string("val");
// Following results in syntax error
// error: no match for ‘operator<<’ in ‘Util().Util::m_os <<
(Util()).m_os << std::string("key") << "=" << std::string("val");
// ----------- Using named instance - output matches expected
// Block results in print "akey=val"
{
Util inst;
inst.m_os << char('a') << std::string("key") << "=" << std::string("val");
}
// Block results in print "Plain old C string key=val"
{
Util inst;
inst.m_os << "Plain old C string " << std::string("key") << "=" << std::string("val");
}
// Block results in print "key=val"
{
Util inst;
inst.m_os << std::string("key") << "=" << std::string("val");
}
return 0;
}
(Util()) creates a temporary object. As a result, (Util()).m_os is also a temporary object.
There are some definitions of operator<< as a member function, and some other definitions of it as a freestanding function. The former work on temporary objects, the latter does not, because a temporary cannot be bound to a reference-to-stream. Simplifying your code to a full example:
#include <stdio.h>
struct stream
{
stream& operator<<(int)
{ puts("operator<<(int)"); return *this; }
};
stream& operator<<(stream& s, char)
{ puts("operator<<(char)"); return s; }
struct streamwrapper
{
stream s;
};
int main()
{
streamwrapper w;
w.s << 'a'; // outputs operator<<(char)
streamwrapper().s << 'a'; // outputs operator<<(int)
}
Since the overloads you expected are unavailable, yet others are not, those other overloads get used instead of giving you a hard compiler error.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This is my code:
#include <iostream>
#include <string>
using namespace std;
class C
{
private:
string str;
friend void func();
};
void func()
{
str = "Lala";
cout << str << endl;
}
int main()
{
func();
}
I don't understand why this doesn't work.
In my bigger project I want to acces private variables of a class with a function out of class.
Here I made a class C and made a function func(); to be its friend.But still I can't use it's private variables in function.
What I did wrong and is there a better way to do this?
It doesn't work because void func(); is not a member function of the class, it's just declared as a friend function to it, meaning it can access the private members.
You have no instance of the class C, so you can't possibly refer to any valid str variable.
Next time, please also quote the errors you get. In this case, there will be a compile error stating the symbol "str" has not been defined within func().
If you want to access the member str of a class instance of C, you need such an instance, as in:
void func(){
C c;
c.str = "Lala";
cout << c.str << endl;
}
func() is not a member function, and it is not receiving any parameter of type C, what object is it supposed to operate on?
func must either be a member function of C (in which case you'll invocate it over an instance of C, and friend is not necessary), either a function that receives some parameter of type C (or create a local C object), on which it can work on, even accessing its private fields.
This doesn't work since str is not defined inside func().
You should have an instance of C.
void func()
{
C foo;
foo.str = "Lala";
cout << str << endl;
}
If you need to you can pass the C instance as a parameter:
void func(C &foo)
{
foo.str = "Lala";
cout << str << endl;
}
The problem
Let's look at your code piece by piece:
#include <iostream>
#include <string>
using namespace std;
Just a short note here: It is a bad idea to use using namespace std;.
class C
{
private:
string str;
friend void func();
};
Here you define a class C. You declare that objects of this class will contain a string, which is private (i.e. may only be accessed by class members and friends), and you declare the global function void func() a friend, that is, it is allowed to access the private members (in this case str) of the class C and of any object of type C. Note that apart from that permission, func is in no way related to the class C.
void func()
{
str = "Lala";
cout << str << endl;
}
Here you try to assign to a variable str which you never declared. Remember that there's no relation of func to the class C other than that it may access the private members of
C and objects of type C. However, there's no object of type C in sight, and even if there were, there's nothing to tell the compiler from which object str is to be taken, or even that you are speaking about the str in C. I'll remember you again that func is completely independent of C, so the code is interpreted the same way as if C wouldn't have declared it a friend.
int main()
{
func();
}
OK, nothing special here, you're just calling func.
How to fix it
Now, how to fix your code? Well, there are several possibilities:
Supplying objects
Local objects
Since str is a member of objects of class C, you'll need an object of the class. So you could for example do:
void func()
{
C object;
object.str = "Lala";
std::cout << object.str << std::endl;
}
Here you create a local object in func, assign to that object's str member a value and then outputs it. To see that different objects have different members, you can e.g. write:
void func()
{
C object1, object2;
object1.str = "Lala";
object2.str = "Lele";
std::cout << object1.str << " -- " << object2.str << "\n";
}
This outputs Lala -- Lele because the first object's str member has the value "Lala" while the second object's str member has the value "Lele".
Function arguments
Another option is that you pass the object as argument, e.g.
void func(C object)
{
std::cout << object.str << " -- ";
object.str = "Lele";
std::cout << object.str << " -- ";
}
int main()
{
C main_object;
main_object.str = "Lala";
func(main_object);
std::cout << object.str << std::endl;
}
This prints Lala -- Lele -- Lala.
What happens here is that in main an object is created, whose str member is assigned the valeu "Lala". On call to func, a copy of that object is created, which you then access from func. Since it's a copy, it initially also contains the same value "Lala", whichfuncthen outputs. Then the assignment infuncchanges thestrmember *of that copy* to"Lele"and outputs that. The original object is not affected as the output inmain` shows.
So you see, there can be several objects, and it is crucial that you say the str member of which object you want to access.
Now if you do not intend to change the object in the called function, making a copy is just a waste of time, therefore you can also pass it as a reference to const:
void func(C const& object)
{
std::cout << object.str << std::endl;
}
int main()
{
C main_object;
main_object.str = "Lala";
func(main_object);
}
The argument C const& says "I want to directly access the object the caller gives me, but I promise not to change it." The "directly access" part is denoted by the &, and the "I promise not to change it" is denoted by the const. The compiler actually checks that you hold your promise and don't try to change it (that is, if in func you tried to do object.str = "Lele", the compiler would complain (there are ways to tell the compiler to shut up about that, but you shouldn't do that; just keep your promises). However note that this applies again only to that specific object; for example, the following code is completely OK:
void func(C const& object)
{
C another_object;
another_object.str = "Lele";
std::cout << object.str << " -- " << another_object.str << std::endl;
}
int main()
{
C main_object;
main_object.str = "Lala";
func(main_object);
}
This gives no error and prints Lala -- Lele because you're dealing again with different objects.
Of course there may be the case that you do want to change the object you are passed. Then you can just use & without const:
void func(C& object)
{
std::cout << object.str << " -- ";
object.str = "Lele";
std::cout << object.str << " -- ";
}
int main()
{
C main_object;
main_object.str = "Lala";
func(main_object);
std::cout << object.str << std::endl;
}
This prints Lala -- Lele -- Lele.
Now you again directly access the object passed as argument from main, but this time, you don't promise that you don't change it, and indeed you do change it. The output from main demonstrates that indeed main_object was changed.
Making the variable a static member
Now, there's the possibility that you really want there to only ever be one str in C, not a separate one for each object of that type. If you are absolutely positive that this is what you want, then you can make str a static member of the class:
class C
{
private:
static std::string str; // note the keyword "static" here
friend void func();
};
std::string C::str; // You have to have an extra definition for class static variables!
Now you can access str without having an object of C available. However note that you still need to tell the compiler inside func that you want to access the str inside C:
void func()
{
C::str = "Lala";
std::cout << C::str << std::endl;
}
You can also access the variable on object as if it were a member of that object. However be aware that this does not mean that different objects still have their own str. For example, with the changed class definition, we will gett different behaviour for the code from above:
void func()
{
C object1, object2;
object1.str = "Lala";
object2.str = "Lele";
std::cout << object1.str << " -- " << object2.str << "\n";
}
Now we will get the output Lele -- Lele because there's only one str, which does not depend on the object (the syntax object1.str in this case is misleading in that respect; actually here it means "the str defined for the type of object1, that is, C").
void func(C* object)
{
object->str = "Lala";
cout << object->str << endl;
}
Since func is not a member of the class, so you can't call it like object.func(). Thus the function won't know which object of the class you wish to change. So you have to explicitly pass the object pointer to the function. Use a reference would also do.
Or you can declare str as static. But static member will make all instances of the class share the same value.