Right way to initialize a pointer in a constructor - c++

I have the following exercise:
Add code to make it run properly.
class MyInt
{
public:
private:
int* MyValue;
}
int main(int argc,char** argv)
{
MyInt x(1);
...//a bit more code where the actual value of x is going to be used.
return 0;
}
I added as a private property
int val;
and a public constructor
Myint(int x)
{
val = x;
MyValue = &val;
}
I added the int val as a way for the constructor to assign to MyVal an address of an object that is not temporary, as the x.
Is there a neat(er) way to answer this exercise?

I don't see anything in your original problem statement that requires the pointer to be initialized to the address of an int. The minimal code required to fix the example would be to add a constructor that takes an int, and initialize MyValue to nullptr.
class MyInt
{
public:
MyInt(int) {}
private:
int* MyValue = nullptr;
};
int main(int argc,char** argv)
{
MyInt x(1);
return 0;
}
If your compiler doesn't support C++11 then
class MyInt
{
public:
MyInt(int) : MyValue(NULL) {}
private:
int* MyValue;
};

Another way:
MyInt(int x) : MyValue(new int(x)) {}
This doesn't require the additional member. However, you have to make sure that you deallocate the memory in the destructor.
~MyInt() { delete MyValue; }

I'm not really sure why you want to store a pointer to an int inside a class, rather than just storing the value directly (and not have a pointer be the input to the constructor), but assuming you do actually want that, here's how you'd do it:
MyInt(int x):MyValue(new int(x)){}
But this is really, really terrible style, and you have to have a good reason for doing it. You also need to remember to free the pointer at class destruction:
~MyInt(){delete MyValue;}

Related

Initialise values of a struct for use in another file

So I have my class Test.H which has a struct in it.
Class Test{
private:
struct Data
{
char *first;
int number;
int count;
};
Data *myStruct;
I am trying to use the myStruct in my User.C initialiser.
//User.C
#include "Test.H"
Test::Test(const char *alp){
myStruct.number = 0;
}
And I get an segmentation fault and error from valgrind.
I figured initially that it was due to Data* myStruct being in private, but after writing a function like this below:
Data getStruct(){
return myStruct;
}
It will still give me errors when I use it in User.C
You need to construct the struct before you can do anything with it. Calling the default constructor will initialises it's fields to 0.
You had class capitalised, that was wrong. I also don't see a reason why it has to be a pointer, so I removed that. Lastly, I added a destructor in Data so that first will be deleted. I assume it is a cstring, so I used delete[]. If it is something else, delete it in whatever manner is appropriate.
If you must have a pointer, modify the call to the constructor to use new, delete the struct in the destructor ~Test(), and reference members of myStruct with the -> operator.
class Test {
public:
struct Data {
const char* first;
int number;
int count;
~Data() {
delete[] first;
}
};
Test(const char *alp) {
// Default constructor initialises struct's fields to 0.
myStruct = Data();
myStruct.count = 7;
}
private:
Data myStruct;
};

Is it possible change value of Member variable within "const" function?

Value of constant variable can be changed through pointer tricks, but is it possible to do something like this :
class A (){
int x;
public:
void func () const {
//change value of x here
}
}
declare x mutable
class A (){
mutable int x;
public:
void func () const {
//change value of x here
}
};
You have two options:
class C
{
public:
void const_f() const
{
x = 5; // A
auto* p_this = const_cast<C*>(this); // B
p_this->y = 5;
}
private:
mutable int x; // A
int y;
};
A: declare certain members mutable.
B: const_cast to remove constness from the this pointer.
Though this is not appreciated, but C++ provides “Backdoors” which can be used to breach its own regulations, just like dirty pointer tricks. Anyway, you can easily do this by using a casted version of “This” pointer :
class A (){
int x;
public:
void func () const {
//change value of x here
A* ptr = const_cast<A*> (this);
ptr->x= 10; //Voila ! Here you go buddy
}
}
The most important thing to understand here is bitwise/physical/concrete constness and conceptual/meaningwise/logical/abstract constness.
In short:
If the function is conceptually const, make the member data mutable.
Otherwise, make the function non-const.
Just cast 'this', this would be a dirty way to implement your program, do avoid this if you are doing a project or teamwork as others would get confused by this.
class CAST_CLASS (){
int var;
public:
void change_CAST () const {
CAST_CLASS* pointer = const_cast<CAST_CLASS*> (this);
pointer->var= 10;
}};
The other answers don't mention this, but following also modifies "x" (definitely, not advisable):
class A {
int x, &y{x}, *z{&x};
public:
void func () const
{
y = 42; // x is modified now!
*z = 29; // x is modified again!!
}
};

Pointer in constructor and member function return different addresses

HelloI got a problem when i compiled my program.
Why the pointer intArray gives different addresses in constructor and member function display() in same object?Thank you!
#include<iostream>
using namespace std;
class MyClass
{ private:
int* intArray;
int arraySize;
public:
MyClass(int*,int);
~MyClass()
{delete []intArray;};
void display();
};
MyClass::MyClass(int intData[],int arrSize)
{ int *intArray = new int[arrSize];
cout<<intArray<<" "<<endl;
};
void MyClass::display()
{ cout<<intArray<<" "<<endl;
}
int main()
{ int Data[10]={9,8,7,6,5,4,3,2,1,0};
MyClass obj1(Data,10);
obj1.display();
}
In the constructor, you declare a local variable which hides the member. Both members are left uninitialised, so calling display will show the uninitialised value.
You probably want something along the lines of
MyClass::MyClass(int intData[],int arrSize) :
intArray(new int[arrSize]),
arraySize(arrSize)
{
// assuming the input array specifies initial values
std::copy(intData, intData+arrSize, intArray);
}
Since you're dealing with raw pointers to allocated memory, remember to follow the Rule of Three to give the class valid copy semantics. Then, once you're happy with your pointer-juggling skills, throw it away and use std::vector instead.

RAII - store `void*&` or `void**`

I am working on design a wrapper class to provide RAII function.
The original use case is as follows:
void* tid(NULL);
OpenFunc(&tid);
CloseFunc(&tid);
After I introduce a new wrapper class, I expect the future usage will be as follows:
void* tid(NULL);
TTTA(tid);
or
TTTB(tid);
Question:
Which implementation TTTA or TTTB is better? Or they are all bad and please introduce a better one.
One thing I have concern is that after the resource is allocated, the id will be accessed outside of class TTTA or TTTB until the id is destroyed. Based on my understanding, my design should not have side-effect for that.
Thank you
class TTTA : boost::noncopyable
{
public:
explicit TTTA(void *id)
: m_id(id)
{
OpenFunc(&m_id); // third-party allocate resource API
}
~TTTA()
{
CloseFunc(&m_id); // third-party release resource API
}
private:
void* &m_id; // have to store the value in order to release in destructor
}
class TTTB : boost::noncopyable
{
public:
explicit TTTB(void *id)
: m_id(&id)
{
OpenFunc(m_id); // third-party allocate resource API
}
~TTTB()
{
CloseFunc(m_id); // third-party release resource API
}
private:
void** m_id; // have to store the value in order to release in destructor
}
// pass-in pointers comparison
class TTTD
{
public:
TTTD(int* id) // Take as reference, do not copy to stack.
: m_id(&id)
{
*m_id = new int(40);
}
private:
int** m_id;
};
class TTTC
{
public:
TTTC(int* &id)
: m_id(id)
{
m_id = new int(30);
}
private:
int* &m_id;
};
class TTTB
{
public:
TTTB(int* id)
: m_id(id)
{
m_id = new int(20);
}
private:
int* &m_id;
};
class TTTA
{
public:
TTTA(int** id)
: m_id(id)
{
*m_id = new int(10);
}
private:
int** m_id;
};
int main()
{
//////////////////////////////////////////////////////////////////////////
int *pA(NULL);
TTTA a(&pA);
cout << *pA << endl; // 10
//////////////////////////////////////////////////////////////////////////
int *pB(NULL);
TTTB b(pB);
//cout << *pB << endl; // wrong
//////////////////////////////////////////////////////////////////////////
int *pC(NULL);
TTTC c(pC);
cout << *pC << endl; // 30
//////////////////////////////////////////////////////////////////////////
int *pD(NULL);
TTTD d(pD);
cout << *pD << endl; // wrong
}
Both break in bad ways.
TTTA stores a reference to a variable (the parameter id) that's stored on the stack.
TTTB stores a pointer to a variable that's stored on the stack.
Both times, the variable goes out of scope when the constructor returns.
EDIT: Since you want the values modifiable, the simplest fix is to take the pointer as a reference; that will make TTTC reference the actual pointer instead of the local copy made when taking the pointer as a non reference parameter;
class TTTC : boost::noncopyable
{
public:
explicit TTTA(void *&id) // Take as reference, do not copy to stack.
: m_id(id)
...
private:
void* &m_id; // have to store the value in order to release in destructor
}
The simple test that breaks your versions is to add a print method to the classes to print the pointer value and do;
int main() {
void* a = (void*)0x200;
void* b = (void*)0x300;
{
TTTA ta(a);
TTTA tb(b);
ta.print();
tb.print();
}
}
Both TTTA and TTTB print both values as 0x300 on my machine. Of course, the result is really UB; so your result may vary.
Why do you tid at all? It’s leaking information to the client and makes the usage twice as long (two lines instead of one):
class tttc {
void* id;
public:
tttc() {
OpenFunc(&id);
}
~tttc() {
CloseFunc(&id);
}
tttc(tttc const&) = delete;
tttc& operator =(tttc const&) = delete;
};
Note that this class forbids copying – your solutions break the rule of three.
If you require access to id from the outside, provide a conversion inside tttc:
void* get() const { return id; }
Or, if absolutely necessary, via an implicit conversion:
operator void*() const { return id; }
(But use that one judiciously since implicit conversions weaken the type system and may lead to hard to diagnose bugs.)
And then there’s std::unique_ptr in the standard library which, with a custom deleter, actually achieves the same and additionally implements the rule of three properly.
What about wrapping it completely? This way you do not have to worry about managing the lifecycles of two variables, but only one.
class TTTC
{
void* m_id;
public:
TTTC()
: m_id(nullptr)
{
OpenFunc(&m_id); // third-party allocate resource API
}
TTTC(TTTC const&) = delete; // or ensure copying does what you expect
void*const& tid() const { return m_id; }
~TTTC()
{
CloseFunc(&m_id); // third-party release resource API
}
};
Using it is simplicity itself:
TTTC wrapped;
DoSomethingWithTid(wrapped.tid());

C++ unable to set NULL pointer to static variable containing object?

Apologies ahead of time, as I am not even sure how to phrase the question, but I was working on a homework assignment (to which the question is unrelated except that I ran into the problem working on the assignment) and came across certain problem (this is just an extraction and generalization, I left out destructors, etc...):
class idType {
int _id;
public:
int getID() { return _id; }
idType(int in = -1) : _id(-1) {}
};
class Foo {
static int _count;
idType* _id; //int wrapper just for examples sake
public:
Foo() { _id = new idType(_count); ++_count; }
idType* getID() { if(_id) return _id; return NULL; } //ERROR WHEN CALLED FROM BELOW
};
class Bar {
Foo* _foo;
public:
Bar(Foo* foo = NULL) : _foo(foo) {}
Foo* getFoo() { if(_foo) return _foo; return NULL; }
};
int foo::_count = 0;
int main() {
Bar BAR;
if(BAR.getFoo()->getID() && BAR.getFoo()); //RUN TIME ACCESS VIOLATION ERROR
return 0;
};
As I mentioned, this is not the code I am working with, but I believe it more clearly identifies what is happening. BAR passes the getFoo() check, so _foo isn't(?) NULL but getFoo()->getID() faults at if(_id).
Is the static variable somehow preventing any NULL instance of a pointer to that class type from existing?
The reason I asked that at first was because when I commented out the static variable lines in my original program, the program worked fine. HOWEVER, after trying this code (which more or less emulates what I am doing) removing the static variable lines makes no difference, it still faults the same.
This may be simple, but I am at a loss as to what is wrong. Thank you much for any help.
Check pointers before using them.
int main()
{
Bar BAR;
Foo *pFoo = BAR.getFoo();
if (pFoo && pFoo->getID())
{
// do something
}
return 0;
};
You are not creating a Foo instance anywhere, and not passing a Foo* to the Bar constructor, so Bar::_foo gets initialize to NULL, which is what Bar::getFoo() returns. And then your if statement crashes due to your backwards use of short-circuit logic (you are trying to access Foo::getID() before first validating that Bar::getFoo() returns a non-NULL Foo* pointer).
You have to pass pointer to Foo object to BAR
int main() {
Bar BAR(new Foo);
//Reverse the condition, check for pointer validity first
if(BAR.getFoo() && BAR.getFoo()->getID());
return 0;
};
Provide the destructor to cleanup _foo after usage
~Bar() { if(_foo) delete _foo; _foo=NULL; }