Duplicating the contents of a double pointer in c++ - c++

Please refer to this code first:
#include <iostream>
class parent_int{
public:
virtual int get_int() const=0;
virtual void increment_int()=0;
};
class a_int: public parent_int{
public:
int a;
a_int(int _a=0): a(_a){}
virtual int get_int()const override{return a;}
virtual void increment_int()override{a+=1;}
};
class b_int:public parent_int{
public:
int b;
b_int(int _b=0): b(_b){}
virtual int get_int() const override{return b;}
virtual void increment_int() override{b+=2;}
};
int main(){
int n=10;
parent_int **a = new parent_int*[10];
for(int i=0;i<n;i++)
{
if(rand()%2==0)
a[i] = new a_int(i);
else
a[i] = new b_int(i);
}
parent_int **alt_a = new parent_int*[10];
for(int i=0;i<n;i++)
{
//?alt_a[i] = ;
*(alt_a[i]) = *(a[i]);
alt_a[i]->increment_int();
}
for(int i=0;i<n;i++)
{
std::cout<<alt_a[i]->get_int()
<<" "<<a[i]->get_int()<<std::endl;
}
}
My question-
Is there a way by which I can copy my objects in
**alt_a from **a such that even when I make changes to my objects in **alt_a the objects of **a are unaffected?
Constraints-
I am using rand() here is to signify that there is no
way of knowing whether the *a points to a_int or b_int.
The parent function should remain a pure virtual function and should not have any constructors? And even if I place a constructor here I don't think how it will aid me?
This code snippet is just a representation of a problem that I am facing in my C++ project so I cannot take into consideration any changes in the design of my program. I need to use double pointers and in the same way as highlighted in the program.
Things that I have tried -
Just equating alt_a[i] = a[i] without de-referencing , this enables me to run my program but again the changes that I make in alt_a[i] is also represented in a[i]

Related

Send the matrix from class to another class

I have a class that has a matrix
class A{
private:
int matrix[10][5];
};
Also I have other class with method that get matrix and do with it
class B{
public:
void method(/*What to write here?*/){...}
};
So, help to releaze the syntax. How to take matrix from class and send it to other class?
Pass by reference
void method(A& a){...}
If method doesn't need to modify a then pass by const reference
void method(const A& a){...}
Based on the comments below it seems you want something like this
class A
{
public:
void set_coordinates(...) { matrix[...][...] = ...; }
private:
int matrix[10][5];
};
class B
{
public:
void method(A& a) { a.set_coordinates(...); }
};
i.e. pass the object A to method B::method but add sufficient public methods to A so that B can do the work it needs to do. This is what encapsulation is all about.
You can use vector<vector<int> >. That way you can pass them around. Or you can use friend classes, or use double pointers. Let me know if you want any of these I can provide examples.
Using double pointers:
#include <iostream>
using namespace std;
class A{
private:
int **matrix;
public:
A()
{
// since 2D array is array of arrays,
// double pointer is a pointer to array of pointers
// define the matrix, first make matrix point to an array of pointers
matrix = new int*[10];
// now make each element of pointer array
// which is a pointer point to actual array
for(int i=0;i<10;i++)
matrix[i] = new int[5];
// initialize like simple 2D array (another function maybe)
for(int i=0;i<10;i++)
for(int j=0;j<5;j++)
matrix[i][j] = i+j;
}
// note the return-type
int ** getMatrix()
{
return matrix;
}
};
class B{
public:
// wherever you want to access matrix, pass the double pointer
void method(int **matrix){
for(int i=0;i<10;i++)
for(int j=0;j<5;j++)
cout << matrix[i][j] << endl;
}
};
int main() {
// create objects
A a;
B b;
// pass the double pointer to B's method
b.method(a.getMatrix());
return 0;
}

Organising C++ code

I am looking for some advice on how to organise my C++ code.
I have an int array, side, that I would like to be static in the sense that its value is kept constant between calls. This is because my function foo(), will modify the array side recursively and so I don't want copies to be made of side. Furthermore, the size of side can only be determined at compile time from the size of a vector that is passed into the function bar().
I have thought of the following structure to layout such a problem.
I keep a global int pointer, side, which I can then use to point to the address of my int array and then use the pointer *side within foo to do my modifications.
Please can you give me advise on the layout and organisation of this code? I am quite new to C++ so would appreciate any advice on the below structure.
#include <iostream>
#include <vector>
using namespace std;
int *side;
class A {
public:
int foo(bool);
int bar(vector<int>);
void set_n(int n){ class_n = n;};
private:
int class_n;
};
int A::foo(bool fl)
{
int n = class_n;
for(int i = 0; i < n; i++) {
// modify side[] and then recursively call foo
}
return 0;
}
int A::bar(vector<int> t)
{
int size = t.size();
set_n(size);
int a = foo(true);
int *side_local = new int[size];
for(int i = 0; i < size; i++) {
side_local[i] = 0;
}
side = side_local;
return 0;
}
int main()
{
A a;
vector<int> t = {1, 2, 3};
a.bar(t);
return 0;
}
A recursive call can pass a pointer to itself:
void foo(int *pList)
{
foo(pList); // recursive
}
the same list is then being worked on.
That being said, since foo is inside a class you wouldn't need a global either, but a member variable.
class A
{
int *pMemberList;
...
void foo();
}
now foo can see pMemberList all the time.
BUT ... passing it is probably a better option as in the future your class might house 2 lists that you want to do foo on.

Initializing a vector on a class constructor

I'm doing this A class which has a vector of B's. I'm initializing the vector on the constructor of the A class (I'm not sure if this is the right way, but it compiles). Besides this, I'm having a problem because I don't want that when initializing the vector that it initializes himself with the default construtor of B() because this makes me do a for loop to set the value that I want. It would be fine if the vector position stood NULL or stood 0 to size;
class B{
int _t;
public:
B(){ _t = 1; }
B(int t) : _t(t){}
};
class A{
std::vector<B> _b;
public:
A(int size): _b(size){
for(int i = 0; i < size; i++){
_b[i].setNumber(i);
}
};
int main() {
int n = 3;
A _a(n);
return 0;
}
You can simply let the vector be default constructed (empty), then emplace_back into it:
A(int size) {
_b.reserve(size);
for(int i = 0; i < size; i++){
_b.emplace_back(i);
}
}
If you are stuck with a pre-C++11 compiler, you can push_back B objects into it:
A(int size) {
_b.reserve(size);
for(int i = 0; i < size; i++){
_b.push_back(B(i));
}
}
The calls to std::vector::reserve are to avoid re-allocations as the vector grows in size.
It does not compile. class B does not have a setNumber function. Initializing the vector to a size does not require you to do anything. It would just default construct number of objects equal to the specified size. Vector has a reserve member function that allows you to allocate enough memory for some number of elements without actually constructing objects. Perhaps that is what you were seeking. Obviously leaving it empty until you are ready to perform some form of insertion is another option. Hopefully one or more of the posted answers will help.
class A{
std::vector<B> _b;
public:
A(int size){
_b.reserve(size);
}
};

Pointer assignment and segmentation fault

I am fairly new to C++ and I keep getting segmentation fault with pointer assignment with code similar to the following, I know it means I'm accessing memory that hasn't been allocated, but I don't see where:
I have two classes:
class ClassA{ //class a decl.
ClassB** oArray;
unsigned int x;
public:
ClassA(unsigned int X);
void oMember(ClassB* classb);
}
ClassA::ClassA(unsigned int X){ //Constructor for class a
x = X;
oArray = new ClassB* [x];
for (unsigned int i = 0; i < x; i++){
oArray = NULL;
}
}
class ClassB{ //rough decl of class B
public:
getId();
}
I have a class member function that takes in a pointer to another class like this:
void ClassA::oMember(ClassB* classb){
unsigned int cID = classb.getId(); //defined in class b
oArray[cID] = classb; //if cID is less than x defined in constructor, is this legal?
}
I just want to point the cIDth member of the array to classb.
I keep getting segmentation fault with an assignment similar to the above. I don't quite know why, I printed the cID and it is definitely less than the size of the array we declared in ClassA's constructor.
Why is that assignment illegal, or why am I getting a segmentation fault?
As we realized in the chat, I just record the problem here for the reference.
The problem lies in the piece
RegisteredVMs = new VendingMachine *[nVendingMachines];
for (unsigned int i = 0; i < nVendingMachines; i++){
RegisteredVMs = NULL;
}
RegisteredVMs is allocated and immediately set to NULL.
This pointer is accessed later in the VMregister() function which causes the seg. fault.
Pointers are hard and very error-prone. Use them only if there is no other way. Since this is a homework problem and since you says you have no say on the interface, I see that you have to use them.
I think you should change your ClassA to
class ClassA{
std::map<int, std::shared_ptr<ClassB> > mMap;
public:
ClassA();
};
Now class A doesn't need to know the array size and mMap will ensure that you don't have very sparse arrays.
I think classb.getId() should be classb->getId() instead as long as classb is a pointer. Well, that should be compiler error and I don't think it is the reason you get segmentation faults.
Are you sure you instantiated ClassA with that particular constructor? If not, the x and oArray may not be initialised.
I do not have your code. But as I modified your code segment to be following, I find no segmentation faults nor compiler warnings.
class ClassB {
public:
int getId();
};
class ClassA {
ClassB** oArray;
unsigned int x;
public:
ClassA(unsigned int X);
void oMember(ClassB* classb);
};
int ClassB::getId() {
return 0;
}
ClassA::ClassA(unsigned int X) {
x = X;
oArray = new ClassB* [x];
}
void ClassA::oMember(ClassB* classb) {
unsigned int cID = classb->getId();
oArray[cID] = classb;
}
int main(int argc, char** argv) {
ClassA a(12);
ClassB b;
a.oMember(&b);
return 0;
}

C++ / Arduino: dynamic int array

I'm writing a class for the Arduino. It's been going well so far, but I'm sort of stuck now...
I have declared an int array in my class
class myClass
{
public: MyClass(int size);
private:
int _intArray[];
};
When I initialize the class MyClass myClass1(5) I need the array to look like this {0,0,0,0,0}.
My question: what do I need to do so that the array contains 'size' amount of zeros?
MyClass::MyClass(int size)
{
//what goes here to dynamically initialize the array
for(int i=0; i < size; i++) _intArray[i] = 0;
}
Edit: Following up on various replies below, Arduino does not include the standard library so unfortunately std::vector is not an option
Your code as I'm writing this:
class myClass
{
public: MyClass(int size);
private:
int _intArray[];
};
The declaration of _intArray is not valid C++: a raw array needs to have a size specified at compile time.
You can instead instead use a std::vector:
class myClass
{
public:
MyClass( int size )
: intArray_( size ) // Vector of given size with zero-valued elements.
{}
private:
std::vector<int> intArray_;
};
Note 1: some compilers may allow your original code as a language extension, in order to support the "struct hack" (that's a C technique that's not necessary in C++).
Note 2: I've changed the name of your member. Generally underscores at the start of names can be problematic because they may conflict with names from the C++ implementation.
Cheers & hth.,
You should use a std::vector.
class myCLass {
public:
myClass(int size)
: intarray(size) {
for(int i = 0; i < size; i++) intarray[i] = 0;
}
private:
std::vector<int> intarray;
};
You should really use vectors as others have suggested. A work-around could be as shown (in case you do not want to use memcpy or a loop).
This would be useful if you have a really huge array. Note that it would add a level of indirection to access the array.
class myClass
{
public:
myClass(){
mt = T(); // value initialize.
}
private:
struct T{
int _intArray[10];
} mt;
};
int main(){
myClass m;
}
I'll try the following:
class myClass
{
public:
MyClass(int size);
~MyClass();
private:
int* _intArray;
};
MyClass::MyClass(int size) {
_intArray = new int[size];
for (int i=0; i<size; ++i) _intArray[i] =0; // or use memset ...
}
MyClass::~MyClass() {
delete[] _intArray;
}
Or, even better, use a STL vector instead ...
you can use another hack basing on a string value and then populate a limited size array
check this :
https://github.com/Riadam/ViewPort-Array-Shifter-for-Arduino-Uno.git