The code below
#include <iostream>
class A
{
public:
int x;
double y;
A(int x_, double y_) : x(x_), y(y_)
{
}
void display(void) const;
};
class B
{
public:
static A staticObject;
};
void A::display(void) const
{
std::cout << x << ' ' << y << std::endl;
B::staticObject.x = 42;
B::staticObject.y = 3.5;
std::cout << x << ' ' << y << std::endl;
}
A B::staticObject(19, 29.3);
int main(void)
{
B::staticObject.display();
return 0;
}
prints out
19 29.3
42 3.5
and this makes me wonder:
Is it always safe to let a const member function modify the object it is called from via other means?
Further, is there any worst-case scenario that could be prevented if that member function (here display) were not declared as const?
Your code is valid and works, because display() is const but only with respect to its containing class, A. This has no impact on its ability to modify fields accessed another way--in your case via non-const public access to the two fields.
However, this code is terrible and scary.
what do you think as "safe"?
The only assumption you should make of a const member function is that it will not modify the current object it is in (this pointer). Constness though is not runtime enforced but during compilation time.
So when you "trick" your compiler with the help of static variables it cannot detect that you are actually accessing the same instance. The staticObject in B can also point to another A than the one it's being called from.
To be able to check it would require runtime checks which c++ does not do.
Related
To understand the problems with object slicing, I thought I have created a horrible example and I was trying to test it. However, the example is not as bad as I thought it would be.
Below is a minimal working example, and I would appreciate if you helped me understand why it is still "working properly". It would be even better if you helped me make the example worse.
#include <functional>
#include <iostream>
template <class T> class Base {
protected:
std::function<T()> f; // inherited
public:
Base() : f{[]() { return T{0}; }} {} // initialized
virtual T func1() const { return f(); }
virtual ~Base() = default; // avoid memory leak for children
};
template <class T> class Child : public Base<T> {
private:
T val;
public:
Child() : Child(T{0}) {}
Child(const T &val) : Base<T>{}, val{val} { // initialize Base<T>::f
Base<T>::f = [&]() { return this->val; }; // copy assign Base<T>::f
}
T func1() const override { return T{2} * Base<T>::f(); }
void setval(const T &val) { this->val = val; }
};
template <class T> T indirect(const Base<T> b) { return b.func1(); }
int main(int argc, char *argv[]) {
Base<double> b;
Child<double> c{5};
std::cout << "c.func1() (before): " << c.func1() << '\n'; // as expected
c.setval(10);
std::cout << "c.func1() (after): " << c.func1() << '\n'; // as expected
std::cout << "indirect(b): " << indirect(b) << '\n'; // as expected
std::cout << "indirect(c): " << indirect(c) << '\n'; // not as expected
return 0;
}
The output I get when I compile the code is as follows:
c.func1() (before): 10
c.func1() (after): 20
indirect(b): 0
indirect(c): 10
I would expect the last line to throw some exception or simply fail. When the base part of c gets sliced in indirect, there is no this->val to be used inside the lambda expression (I know, C++ is a statically compiled language, not a dynamic one). I have also tried capturing this->val by value when copy assigning Base<T>::f, but it did not change the result.
Basically, my question is two folds. First, is this undefined behaviour, or simply a legal code? Second, if this is a legal code, why is the behaviour not affected by slicing? I mean, I can see that T func1() const is called from the Base<T> part, but why is the captured value not causing any trouble?
Finally, how can I build an example to have worse side-effects such as memory access type of problems?
Thank you in advance for your time.
EDIT. I am aware of the other topic that has been marked as duplicate. I have read all the posts there, and in fact, I have been trying to duplicate the last post there. As I have asked above, I am trying to get the behaviour
Then the information in b about member bar is lost in a.
which I cannot get fully. To me, only partial information seems to be lost. Basically, in the last post, the person claims
The extra information from the instance has been lost, and f is now prone to undefined behaviour.
In my example, f seems to be working just as well. Instead, I just have the call to T Base<T>::func1() const, which is no surprise.
There is no undefined behavior with your current code. However, it's dangerous and therefore easy to make undefined behavior with it.
The slicing happen, and yet you access this->val. Seems like magic, but you're just accessing the this->val from Child<double> c from your main!
That's because of the lambda capture. You capture this, which points to your c variable in your main. You then assign that lambda into a std::function inside your base class. You base class now have a pointer to the c variable, and a way to access the val through the std::function.
So the slicing occurs, but you access to the unsliced object.
This is also why the number is not multiplied by two. The virtual call resolves to base, and the value of val in c in your main is 10.
Your code is roughly equivalent to that:
struct B;
struct A {
B* b = nullptr;
int func1() const;
};
struct B : A {
int val;
explicit B(int v) : A{this}, val{v} {}
};
int A::func1() const {
return b->val;
}
int main() {
B b{10};
A a = b;
std::cout << a.func1() << std::endl;
}
I have a class such as
class Stuff
{
private:
int x;
virtual int buisness()
{
return 42;
}
public:
Stuff(){
x = 5;
}
Given a pointer to an instance of this class
Stuff stuff;
void* thing = &stuff;
How would I get a pointer to the variable x and a pointer to the virtual function table of that class using just the pointer "thing"?
Edit: to clarify this was a challenge sent to me and I have been assured that it is not a trick question.
How would I get a pointer to the variable x and a pointer to the virtual function table of that class using just the pointer "thing"?
You can't without casting thing back to the original type:
Stuff* stuff2 = reinterpret_cast<Stuff*>(thing);
and at least that doesn't redeem you from privacy policies of that class, and how you could access class member pointers publicly.
The actual layout is implementation defined, and trying to use offsets from thing and size assumptions is beyond standard c++ mechanisms.
It sounds like you want to circumvent the private member access policies of a class with known layout of these members. Here's an extremely dirty hack:
Disclamer: Don't do that in production code!!
#include <iostream>
class Stuff {
private:
int x;
virtual int business() {
std::cout << "Have that 42 ... " << std::endl;
return 42;
}
public:
Stuff() {
x = 5;
}
};
struct StuffProxy {
// Make the layout public:
int x;
virtual int business();
};
int main() {
Stuff stuff;
void* thing = &stuff;
// Here's the nasty stuff
StuffProxy* stuffProxy = reinterpret_cast<StuffProxy*>(thing);
int* addrX = &(stuffProxy->x); // Get the address of x
std::cout << "x = " << *addrX << std::endl;
typedef int (Stuff::*StuffFunc)();
StuffFunc stuffFunc = (StuffFunc)(&StuffProxy::business);
std::cout << "business() = " << (stuff.*stuffFunc)() << std::endl;
}
Output:
x = 5
Have that 42 ...
business() = 42
Live Demo
The above works because it's guaranteed that class and struct will have the same layout in a c++ compilers implementation, with the only difference of the members visibility during compilation.
So if you have the layout of a class (e.g. from a header), and you are willing to maintain that over the lifetime of your project, you can provide such proxy like above to access the private stuff from a class.
To access the private member x:
1) Declare the function, that needs to access x, as a friend of the class.
2) Change access to public.
3) Write public getter or setter functions.
4) Change your design; Other classes should not know about member variables.
This may be compiler dependant.
I just made a char array from the pointer "thing"
char *array;
array = (char*)thing;
Then traverse that array until I found the private variables
int x = array[8];
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
I have a class(A) that contains for example five variables (parameters t,z,y,d and f) and I created an object(A) of a type class(A). Then I have many functions (X,U,M) that are included in the "main.cpp", each function is defined to take only three or four parameters that are already exist in the object(A). for example function(X) uses the variables (t,y and z only)
Instead of passing the parameters as void function(X) (int t, int y, double z){} can I pass only the object(A) and let each function selects its parameters by just looking for what it needs from object(A)'s parameters as follow (if this exist)?
void function(X) (A()){}
I would like to avoid using the following.
void function(X) (A.t, A.y, A.z){}
(Please note I am new to c++ and I am working in Qt Creator.)
Yes, you can pass an object to a function. There are several ways to pass the an instance of a class to a function:
by value (if function() needs to modify obj but the caller does not need to see the changes and copying is inexpensive):
void function(A obj) {}
by reference (if function() modifies obj and changes must be visible to the caller):
void function(A& obj) {}
by const reference (if function() does not modify obj):
void function(A const& obj) {}
by rvalue reference (c++11):
void function(A&& obj) {}
The class A will need to provide access to it's members.
Easy
class A
{
public:
double z;
};
void func(const A &obj)
{
// Do something with obj.z
std::cout << obj.z << std::endl;
}
int main()
{
A myObj;
myObj.z = 100;
func(myObj);
}
Joachim's explanation is what you need, except that the object should be passed as either a pointer or a reference, to ensure it isn't getting copied.
void someFunction(C& c)
// Accept a reference to a 'C' object
{
// Joachim's code
// This method doesn't change the main from Joachim's
// answer.
}
void someFunction(C* c)
// Accept a pointer to a 'C' object
{
std::cout << "The member i_ is " << c->getI() << std::endl;
// Note the use of '->', not '.' to access the object's method.
}
void main()
{
C c;
c.setI(1);
someFunction(&c);
// The '&' means 'address of' in this context. I.E. you're passing a pointer.
}
If the member fields are public you can access them from any function. If the are not public you have to add member functions to the class to get the values, so called "getter" functions.
#include <iostream>
class C
{
public:
int getI() const { return i_; }
void setI(const int i) { i_ = i; }
private:
int i_;
}
void someFunction(C c)
{
std::cout << "The member i_ in c is " << c.getI() << '\n';
}
int main()
{
C c;
c.setI(123);
someFunction(c);
}
I have a main method in my main.cpp that I would like to display the value of a constant int I have declared.
I added a DeclareConstant class.
Here is my DelcareConstant.h
#pragma once
class DeclareConstant
{
public:
const int x;
Part1(void);
Part1(int x);
~Part1(void);
double getX(){return x;}
};
And source
#include "Part1.h"
Part1::Part1() : x(55){
}
How can I access X so I can display it in my main method? I need to check if I'm even initializing it correctly.
You can access x through getter function getX(), for example:
DeclareConstant dc;
std::cout << dc.getX() << std::endl;
Or
DeclareConstant dc;
std::cout << dc.x << std::endl;
However, you should define your getX like this:
class DeclareConstant
{
public:
int getX() const {return x;}
private:
const int x;
};
And please hide your class member.
If all your instances use the same constant value, you can make it static. This has a couple of advantages.
You can define it as below.
class Part1{
public:
static const int x = 42;
Part1(void);
Part1(int x);
~Part1(void);
double getX(){return x;}
};
and access it simply as Part1::x. You should make getX static as well, then you can do Part1::getX().
This will not work if each instance has its own const value.
You need an object or an instance of DeclareConstant to access the DeclareConstant's x member.
DeclareConstant myConst;
std::cout << myConst.x << std::endl; // Use x
But for your possible purpose and intentions you could make x as a static member.
class DeclareConstant {
public:
static const int x = 55;
// ...
}
You now don't need an instance to get the value of x:
std::cout << DeclareConstant::x << std::endl; // Use x