Polymorphism Problem C++ - c++

I have these classes:
class A
{
};
class B : public A
{
public:
B(int val);
private:
int* m_int;
};
B::B(int val)
{
m_int = &val;
}
I call the code like so, inside 1 function, i know the vars will be destroyed once they are out of scope, but I only need them in this function:
{
...
int _int = 0;
B obj(_int);
A *obj2 = &obj;
_int++;
...
}
The problem is that _int is changing to 1, but m_int stays the same. I need m_int to reflect what the value in _int is, without the need to update it with code. I thought having a pointer to a memory location would work?
The second problem is that when I hover my mouse over obj2, to see the values of obj, I get the message "children could not be evaluated".

I'm not too sure whether the following is good advice for a novice, but using a reference like this would work:
class B : A
{
public:
explicit B(int& val);
private:
int* m_int;
};
B::B(int& val)
{
m_int = &val;
}
I'm a bit worried that it is actually a sign of bad design. If it is just for learning purposes, go right ahead, understanding is always important

The pointer m_int will stay the same but the value pointed to *m_int will change, you'll also have to pass the value val by reference to the function.
EDIT: Saw your edited question, since this is done from the constructor you can do:
class B : A
{
public:
B(int& val) : m_int(val) {}
private:
int& m_int;
};
To have m_int reference the same variable.

If you want to change value of _int you should pass it's pointer, they way you're doing now is call by value.
B::B(int* val)
{
m_int = val; // not ref
}
and m_int should be of type int* not int
For second problem, you're storing a value of derived class in a pointer to base, So when you try to see what's inside obj2 you only see the part of type base, that's why you get message children cannot be evaluated.
Edit--
If you want to see what actually is in obj2, you should cast it to derived type again. And you may not always know that at runtime...

Related

How is it possible to assign "this" pointer to field?

As far as I know, "this" pointer is the parameter that is inserted into function by Compiler like below :
class Sample {
private:
int a;
public:
void setA(int a) {
this->a = a;
}
};
Sample ob;
ob.setA(5); -> ob.setA(&ob, 5);
class Sample {
private:
int a;
public:
void setA(Sample* this, int a) {
this->a = a;
}
};
Btw, I found something confusing code that assigning the "this" pointer to const field. (Consult below)
class Test {
int data;
public:
Test* const test = this;
Test(int data = 1) : data(data) { }
Test(Test &test) : data(test.data) { }
};
(It has no compile Errors and runs well!)
If it is true that "this" pointer is conveyed via function, How can it be?
I have no idea..
Could you give me some advice please? I'm appreciate for your any replies.
This syntax:
Test* const test = this;
comes from C++11. It means "initialize test to this inside any non-copy constructor which does not already initialize test explicitly".
As a result, this code is executed inside the constructor, and this is perfectly valid. However, the benefit of doing this sort of initialization is unclear, and dependening on the usage of test might be dangerous.
The properties of the class (Test.test in this case) are initialized implicitly by code that is generated by the compiler. There is a function, and it does receive the this pointer, but it's all generated by the compiler which is why you can't see it.

c++ access main objects from other file

I wonder how it is possible to access an object that was created in the main function from another class.
main.cpp
#include"ClassA.h";
#include"ClassB.h";
int main()
{
ClassA objectA;
return 0;
}
ClassA.h
#pragma once
class ClassA
{
public:
ClassA():_privateVar(100)
{};
~ClassA()
{};
//Getters
float getPrivateVarA(){ return _privateVarA; };
//Setters
void setPrivateVarA(float privateVarA){ _privateVarA = privateVarA; };
private:
//Just a value
float _privateVarA;
};
ClassB.h
#pragma once
class ClassB
{
public:
ClassB():_privateVarB(50)
{ };
~ClassB()
{ };
//This is what i´m trying to achieve: Acces objectA
// like this: objectA.getPrivateVarA(); or objectA.setPrivateVarA;
int getPrivateVarB(){return _privateVarB;};
private:
int _privateVarB;
};
I've been all week searching for an answer to this and found nothing...
If anyone knows of some books or have any information on how I can get there would be grateful.
Thank you.
You placed your question in the middle of the ClassB declaration. You can't execute code there. Whatever you do must be done from within a function.
A function in ClassB can be defined so that it accepts a reference or pointer to a ClassA. Then that reference can be used to call getPrivateVarA().
In other words, if class B needs to access a class A then it is up to your code to initialize B with the required reference. This can be done when creating the B object, or when calling a method of the B object.
objectA has function-local scope within main(). By definition, objects can be directly accessed only within their visible scope. That's what C++ is all about.
Of course, if you pass a reference or a pointer to this object, to some other function, that other function can access the instantiated object indirectly, via the pointer or the reference.
I can't say with 100% certainty that you can't, but you definitely should not be doing that. If you want to use an object created in a different scope then you need to pass it into the scope you want to access it from either by value, reference or via a pointer.
First Class A:
class A {
public:
ClassA() : _privateVar(100) {}
~ClassA() {}
float getPrivateVarA() { return _privateVar; }
void setPrivateVarA(float val) { _privateVar = val; }
private:
float _privateVar;
};
First Class B:
class B {
public:
ClassB() : _privateVar(50) {}
~ClassB() {}
// by copy
float getPrivateVarB_byCopy(ClassA a) {
return _privateVar + a.getPrivateVarA();
}
// by reference
float getPrivateVarB_byRef(ClassA &a) {
return _privateVar + a.getPrivateVarA();
}
// by pointer
float getPrivateVarB_byPointer(ClassA *a) {
return _privateVar + a->getPrivateVarA();
}
float setPrivateVarB(float val) { _privateVar = val; }
private:
float _privateVar;
};
Now for main.
int main(void) {
ClassB b;
ClassA a; // for copy and ref
ClassA *a2 = new ClassA(); // for pointer
b.getPrivateVarB_byCopy(a); // => 150
b.getPrivateVarB_byRef(a); // => 150
b.getPrivateVarB_byPointer(a2); // => 150
delete a2; // clean up pointer
return 0;
}
Although your example this type of access is really not a good idea, not sure why you'd want to go about doing things this way.

how to set internals of a class

Hi I am pretty new to C++ and im converting C code to C++. I started by converting all the structs to classes, and added accessors and mutators for the internals, but some structs have other structs inside them. I want to know the best method for setting the internals of a class within a class, such as
struct1.struct2.struct3.i = 5;
where i is an int. Should I be passing as reference using accessors? but seeing as accessors tend to be const would this be something I should do?
something like
class1.get_class2().get_class3().set_i(5) or something if it can be done in this kind of format.
This is probably a dumb question but i have no idea how to do it, Thank You
class1.get_class2().get_class3().set_i(5)
is possible if get_class2() is non-const and returns a non-const pointer reference.
However, this approach completely breaks the encapsulation. The users of class1 should not (and must not) know that class1 uses class2 inside and that in turn uses class3 inside.
If a setter-API is absolutely necessary, then a better approach is do it hierarchically. For example
// User
class1.set_i( 5 );
// class1
class1::set_i( int x ) { class2_obj.set_i( x ); }
// class2
class2::set_i( int x ) { class3_obj.set_i( x ); }
// class3
class3::set_i( int x ) { i_ = x; }
I am not so sure about that ... did you put a class inside a class or an object inside a class ?
something like :
class OBJ1
{
//methods , and other stuff
}
class OBJ2
{
public OBJ1 *O ;
}
is valid , so you can acces a method like :
OBJ2 *N2 ;
N2->O->some_method();
however , something like
class OBJ2
{
class OBJ1;
}
is not valid :P
again... not sure if this is exactly what you asked ...
If you really have a good reason to access your member object via getters and setters, you can do the following:
class A {
public:
void f() const {}
};
class B {
public:
const A &get_a() const {
// the returned reference will be read-only, i.e. only non-const member
// functions can be called, and public members can not be written.
// it needs to be stored in a const A & object.
return a;
}
A &get_writable_a() {
return a;
}
void set_a(A &a) {
//make sure that the assignment operator of A will take care of all the
//dirty internals, such as internal buffers that need to be deleted.
this->a = a;
}
private:
//the member
A a;
};
int main() {
B b;
b.get_a().f();
}
If you don't have a good reason to do so, I'd recommend to simply make it a public member, and access it directy:
class A {
public:
void f() const {}
};
class B {
public:
A a;
};
int main() {
B b;
b.a.f();
}
Isn't that simply much more elegant?
Note that you can use friend to specify other functions or classes that are allowed to directly access your private members.
As was also pointed out in an other answer, in most cases it is a bad idea to make a member object visible to the outside at all.

Memory allocation and releasing memory

I'm a newbie using V++ and I've been wondering about some memory behavior.
I wrote similar classes to what is causing me problems. The questions are
written in the comments of the code.
class A
{
private:
int _number;
public:
A(int number) : _number(number)
{}
const int& getNumber() const
{
return _number;
}
void setNumber(const int& number)
{
_number = number;
}
}
class B
{
private:
A _a;
bool _hasA;
public:
B() : _hasA(false)
{}
B(const A & a) : _a(a), _hasA(true)
{}
void setA(const A & a)
{
_a = a;
}
const A& getA() const
{
return _a;
}
const bool hasA() const
{
return _hasA;
}
void removeA()
{
// ??
}
}
int main()
{
A a(5);
B b1; // Is the A space allocated even if no value is affected to it ?
B b2(a);
b1.setA(b2.getA()); // I actually want to move "a" from b2 to b1 without leaving it in b2
b1.removeA(); // Do I need to write a removeA() function and how would it be?
}
b1.setA(b2.getA()); copies A into b1 too instead of moving it.
Thanks for your help.
EDIT: To answer those who are confused like I just was:
Me : I just understood that when instanciating b1 it needed the A::A() constructor. I thought it'd be like "null" or something if I created b1 without instantiating _a.
Zac Howland: #SanjamX I see your confusion now. In managed languages, (most) everything is a pointer, so if you do not instantiate it (e.g. A a instead of A a = new A()), it is just a null pointer. In C/C++, if you declare something as A a, you instantiated it "on the stack". It is an automatic variable that will be deallocated when it goes out of scope. You are still instantiating it, however. This question may help you understand better.
B b1();
That does not do what you think it does. It is declaring a function b1 that takes no parameters and returns a B.
b1.setA(b2.getA());
b1.removeA();
Because of the previous situation, the 2 lines above will give you a compiler error.
The "move" you are asking about will actually be a copy (in this case). You can use the C++11 move semantics to do an actual move, but it is entirely unnecessary with the current code. Alternatively, you can change your class to do a move using pointers (which could potentially be useful) - which would use std::unique_ptr<A> _a, instead of A _a.

How to pass a linc to class function and call it?

So I have a class like
class mySafeData
{
public:
void Set( int i )
{
myMutex.lock();
myData = i;
myMutex.unlock();
}
void Get( int& i)
{
myMutex.lock();
i = myData;
myMutex.unlock();
}
private:
int myData;
boost::mutex myMutex;
};
its instance is running. Lets call instance A. I want to create a new class that would take as a start up argument some kind of link to Getter from A and would be capable to somehow save link to thet getter for calling it inside its private methods vhen needed. how to do such thing?
Sounds like you want something like this:
class myOtherData
{
public:
myOtherData(mySafeData& dataSource) :
myDataSource(&dataSource)
{}
private:
// note that if you take the advice in the comments,
// you don't need this wrapper function at all,
// it's simple just to call myDataSource.Get()
int GetData()
{
int result;
myDataSource.Get(result);
return result;
}
mySafeData* myDataSource;
};
mySafeData a;
myOtherData b(a);
// b uses a as its data source (make sure it lives as long!)
I'm not sure what you mean by linc/link. Are you asking for anything more than this pattern?
class Foo {
public:
Foo(mySafeData& d) : data(d) {}
int someFunction() {
int i;
data.get(i);
return i;
}
private:
mySafeData& data;
};
...
Foo f(a);
What's wrong with pointers? Smart, Shared, Scoped... I'll use standard pointers for now.
class B
{
public:
B(mySafeData* ptr) // constructor takes a memory pointer as parameter
:SafeData_ptr(ptr)
{
SafeData_ptr->foo(); // call public function from class A
}
~B() // destructor
{
}
private:
mySafeData* SafeData_ptr; // will hold the mem address of instance A when
// this class is initialized
};
Later on your code, when you have instance A ready, you would do something like this:
B b_demo(&A); // &A passes the memory address of the instantiated object
// and A::foo() will be automatically called when B is constructed.
This is probably not the smartest way to do it, but I think it illustrates the idea.