I know that the this pointer is implicitly passed to member functions when they are called. When I try to get the address of this pointer (via &this), though, I get the compiler error "lvalue required". Why is this?
class st
{
int a,b;
public :
void print()
{
cout << &this; //gives lvalue required... why?
cout << this; //will print address of object.
}
}
this is not an lvalue but an prvalue. From [class.this]:
In the body of a non-static (9.3) member function, the keyword this is a prvalue expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*. If the member function is declared const, the type of this is const X*, if the member function is declared volatile, the type of this is volatile X*, and if the member function is declared const volatile, the type of this is const volatile X*.
Emphasis mine
& requires an lvalue so you cannot get the address of this.
Because this pointer is a rvalue. this pointer is a constant value, it is passed to the member function like a local variable, so it's value is stored in a memory location that would become invalid when returning from that function.
Presumably you're trying to print out the values in the object. cout doesn't know how to do this, and you have to teach it.
cout << *this;
might do this if cout knew how to do it, but you can teach it. Here's an example that is more natural c++. (You should also consider a constructor).
#include <iostream>
using namespace std;
class st
{
public:
int a,b;
};
std::ostream& operator<<(std::ostream& s, const st& val)
{
return s << "a:" << val.a << " b:" << val.b ;
}
int main() {
st foo;
foo.a = 1;
foo.b = 2;
cout << "foo is " << foo << endl;
}
Related
I have learned that function name equals function address
like this:
void func(){}
void main() { cout << func; }
But when I used the same code to print memeber function, it went wrong.
class Test{
public:
void func() {}
void printFunc1() {
cout << func << endl;
}
void printFunc2() {
void (Test::*ptrtofn)() = &Test::func;
cout << (void*&)ptrtofn << endl;
}
};
printFunction2() work but printFunction1() doesnt
What makes the difference?
Member function's name is not member function's address?
Is there any reason?
member function != standalone function
Only standalone functions can be converted to pointer implicitely.
4.3 Function-to-pointer conversion [conv.func]
1 An lvalue of function type T can be converted to a prvalue of type “pointer to T.” The result is a pointer to the function. 58
58) This conversion never applies to non-static member functions
because an lvalue that refers to a non-static member function cannot
be obtained.
Please understand "func" is the member function of the class . accessing it directly is itself a compilation error .Rather you should try to use pointer to member function as you have done in printFunction2:
Else if func is function outside the class scope .Then it can be done as below :
#include <iostream>
using namespace std;
void func() {cout<<"\n calling func\n";}
void printFunc1() {
cout << endl<<hex<<(void*)func << endl;
}
int main() {
printFunc1();
return 0;
}
My program is not compiling and keeps outputing the same error "non-lvalue in assignment." I've tried looking around the internet to why this is happening but I can't seem to find anything. I would really appreciate some input.
#include <iostream>
using namespace std;
class Class
{
public:
Class()
{
Var=0;
}
private:
int Var;
friend void Friend(Class &object);
};
void Friend(Class &object)
{
&object.Var=99;
cout << &object.Var << endl;
}
int main()
{
Class testobject;
Friend(testobject);
}
You won't need the & inside the function
The problem is this line &object.Var=99; You taking the address of object and than accessing .Var, this cant work.
Seems you missunderstood references, you dont have to dereference them (unlike pointer).
Change your function to this:
void Friend(Class &object)
{
object.Var=99;
cout << object.Var << endl;
}
Change the function definition to
void Friend(Class &object)
{
object.Var=99;
cout << object.Var << endl;
}
The reason of the error is described in the following quote of the C++ Standard
if the type of the expression is T, the result has type “pointer to T”
and is a prvalue
Replace &object.Var=99; with object.Var=99; and cout << &object.Var << endl; with cout << object.Var << endl;
When passing an argument, & denotes that you receive the variable as a reference.
void Friend(Class &object) means you get the reference of testobject in object.
&object.Var implies address of object.Var. You cannot assign to that. Hence the error non-lvalue in assignment.
Take this example code
#include <iostream>
using namespace std;
class Address
{
public:
mutable unsigned key;
Address() : key(0) {};
Address(int a) : key(a) {};
// const Address but compiler lets us modify it anyway!
Address(const Address &n) : key(++n.key) {};
void showKey() { cout << "key is " << key << endl;}
void modifyKey(int k) { key = k;}
};
int main()
{
cout << "Address a " << endl;
Address a;
a.showKey();
cout << "Address b " << endl;
Address b(a);
b.showKey();
if (b.key == a .key)
cerr << "Wow the compiler doesn't care about const correctness" << endl;
return 0;
}
The copy constructor of the Address class says that n if a reference to a constant Address object. Therefore I expect modifications to the object referenced by n to be disallowed. It seems that directly manipulating n's fields is allowed by the compiler. However I did notice if I add a non const method to Address and call it on n inside the copy constructor (e.g. n.myNonConstMethod()) the compiler will complain.
I am surprised that this code compiles (I've tried g++ and clang++ and they compile with out errors or warnings). Have I misunderstood the use of const (it wouldn't be the first time!) or are these compiler bugs?
Pulled from MSDN:
This keyword [mutable] can only be applied to non-static and non-const data members of a class. If a data member is declared mutable, then it is legal to assign a value to this data member from a const member function.
I'm fairly new to C++, and I don't understand what the this pointer does in the following scenario:
void do_something_to_a_foo(Foo *foo_instance);
void Foo::DoSomething()
{
do_something_to_a_foo(this);
}
I grabbed that from someone else's post on here.
What does this point to? I'm confused. The function has no input, so what is this doing?
this refers to the current object.
The keyword this identifies a special type of pointer. Suppose that you create an object named x of class A, and class A has a non-static member function f(). If you call the function x.f(), the keyword this in the body of f() stores the address of x.
The short answer is that this is a special keyword that identifies "this" object - the one on which you are currently operating. The slightly longer, more complex answer is this:
When you have a class, it can have member functions of two types: static and non-static. The non-static member functions must operate on a particular instance of the class, and they need to know where that instance is. To help them, the language defines an implicit variable (i.e. one that is declared automatically for you when it is needed without you having to do anything) which is called this and which will automatically be made to point to the particular instance of the class on which the member function is operating.
Consider this simple example:
#include <iostream>
class A
{
public:
A()
{
std::cout << "A::A: constructed at " << this << std::endl;
}
void SayHello()
{
std::cout << "Hi! I am the instance of A at " << this << std::endl;
}
};
int main(int, char **)
{
A a1;
A a2;
a1.SayHello();
a2.SayHello();
return 0;
}
When you compile and run this, observe that the value of this is different between a1 and a2.
Just some random facts about this to supplement the other answers:
class Foo {
public:
Foo * foo () { return this; }
const Foo * cfoo () const { return this; /* return foo(); is an error */ }
};
Foo x; // can call either x.foo() or x.cfoo()
const Foo y; // can only call x.cfoo()
When the object is const, the type of this becomes a pointer to const.
class Bar {
int x;
int y;
public:
Bar () : x(1), y(2) {}
void bar (int x = 3) {
int y = 4;
std::cout << "x: " << x << std::endl;
std::cout << "this->x: " << this->x << std::endl;
std::cout << "y: " << y << std::endl;
std::cout << "this->y: " << this->y << std::endl;
}
};
The this pointer can be used to access a member that was overshadowed by a function parameter or a local variable.
template <unsigned V>
class Foo {
unsigned v;
public:
Foo () : v(V) { std::cout << "<" << v << ">" << " this: " << this << std::endl; }
};
class Bar : public Foo<1>, public Foo<2>, public Foo<3> {
public:
Bar () { std::cout << "Bar this: " << this << std::endl; }
};
Multiple inheritance will cause the different parents to have different this values. Only the first inherited parent will have the same this value as the derived object.
this is a pointer to self (the object who invoked this).
Suppose you have an object of class Car named car which have a non static method getColor(), the call to this inside getColor() returns the adress of car (the instance of the class).
Static member functions does not have a this pointer(since they are not related to an instance).
this means the object of Foo on which DoSomething() is invoked. I explain it with example
void do_something_to_a_foo(Foo *foo_instance){
foo_instance->printFoo();
}
and our class
class Foo{
string fooName;
public:
Foo(string fName);
void printFoo();
void DoSomething();
};
Foo::Foo(string fName){
fooName = fName;
}
void Foo::printFoo(){
cout<<"the fooName is: "<<fooName<<endl;
}
void Foo::DoSomething(){
do_something_to_a_foo(this);
}
now we instantiate objects like
Foo fooObject("first);
f.DoSomething();//it will prints out first
similarly whatever the string will be passed to Foo constructor will be printed on calling DoSomething().Because for example in DoSomething() of above example "this" means fooObject and in do_something_to_a_foo() fooObject is passed by reference.
Acc. to Object Oriented Programming with c++ by Balaguruswamy
this is a pointer that points to the object for which this function was called. For example, the function call A.max() will set the pointer this to the address of the object. The pointer this is acts as an implicit argument to all the member functions.
You will find a great example of this pointer here. It also helped me to understand the concept.
http://www.learncpp.com/cpp-tutorial/8-8-the-hidden-this-pointer/
Nonstatic member functions such as Foo::DoSomething have an implicit parameter whose value is used for this. The standard specifies this in C++11 §5.2.2/4:
When a function is called, each parameter (8.3.5) shall be initialized (8.5, 12.8, 12.1) with its corresponding argument. [Note: Such initializations are indeterminately sequenced with respect to each other (1.9) — end note ] If the function is a non-static member function, the this parameter of the function (9.3.2) shall be initialized with a pointer to the object of the call, converted as if by an explicit type conversion (5.4).
As a result, you need a Foo object to call DoSomething. That object simply becomes this.
The only difference (and it's trivial) between the this keyword and a normal, explicitly-declared const pointer parameter is that you cannot take the address of this.
It is a local pointer.It refers to the current object as local object
So from a question asked in another thread, I have thought of a new question and the answer is not obvious to me.
So it appears there is a c++ rule that says if you have a const reference to a temporary, then the lifetime of the temporary is at least as long as the const reference. But what if you have a local const reference to another object's member variable and then when you leave scope - Does it call the destructor of that variable?
So here is modified program from the original question:
#include <iostream>
#include <string>
using namespace std;
class A {
public:
A(std::string l) { k = l; };
std::string get() const { return k; };
std::string k;
};
class B {
public:
B(A a) : a(a) {}
void b() { cout << a.get(); } //Has a member function
A a;
};
void f(const A& a)
{ //Gets a reference to the member function creates a const reference
stores it and goes out of scope
const A& temp = a;
cout << "Within f(): " << temp.k << "\n";
}
int main() {
B b(A("hey"));
cout << "Before f(): " << b.a<< "\n";
f(b.a);
cout << "After f(): " << b.a.k << "\n";
return 0;
}
So when I run this code, I get "hey" as the value everytime. Which seems to imply that a local const reference does not bind itself through life with a passed in member object. Why doesn't it?
b.a is not a temporary so its lifetime is not affected by any references that are subsequently bound to it.
I'm not sure I understand what you're asking. In your code, the only
temporary I see is the A("hey") in the expression that initializes b
in main. And that is copied (using the copy constructor) into b.a
in B::B. After that, there are no more temporaries, anywhere.
More generally, the fact that a temporary is bound to a reference
doesn't necessarily change its lifetime. What extends the lifetime is
the fact that the temporary is used to initialize the reference: in your
case, for example, temp in f will never have an effect on the
lifetime of a temporary, because it is not initialized with a temporary,
but with another reference. And there are exceptions to this rule: if
you use a temporary to initialize a member reference in the initializers
of a class, it's lifetime will still not extend beyond the end of the
constructor, so:
class A
{
std::string const& rString;
public:
A() : rString( std::string( "hey" ) ) {}
std::string get() const { retur rString; }
};
will not work.