Pass array to the derived class in C++ - c++

In Class Dim I created array G and I want to pass it to the derived Class PHYS_FIELD. Instead of output (0..9) it gives (0..0). I realize that it is just a new copy of G but I do not know how to do it correctly.
arr1.h:
#ifndef ARR1_H
#define ARR1_H
#include<iostream>
using namespace std;
template <class T> class arr1
{
public:
T* data;
size_t size;
arr1(const size_t isize)
{ size=isize;
data = new T[size];
}
T & operator ()(size_t const index)
{ return data[index]; }
};
#endif /*ARR1_H */
dim.h:
#ifndef DIM_H
#define DIM_H
#include "arr1.h"
class DIM {
public:
DIM();
protected:
int N;
};
#endif /* DIM_H */
dim.cpp:
#include "arr1.h"
#include "dim.h"
using namespace std;
DIM :: DIM()
{
N=10;
arr1<double> G(N);
for (int i=0; i<N; i++)
G(i)=i;
};
phys_field.h:
#ifndef PHYS_FIELD_H
#define PHYS_FIELD_H
#include "dim.h"
#include "arr1.h"
class PHYS_FIELD : public DIM {
public:
PHYS_FIELD();
arr1<double> G;
};
#endif /* PHYS__FIELD_H */
phys_field.cpp:
#include "dim.h"
#include "phys_field.h"
#include <arr1.h>
using namespace std;
PHYS_FIELD :: PHYS_FIELD(): G(N) {
cout<< " from phys_field.cpp "<<endl;
cout<<N<<endl;
for (int i=0; i<N ; i++)
cout<<i<<" "<<G(i)<<endl;
};
main.cpp:
#include "dim.h"
#include "phys_field.h"
using namespace std;
int main(int argc, char* argv[]){
PHYS_FIELD *F= new PHYS_FIELD();
return 0;
}

modify class arr1 and add a constructor that accepts zero parameters (this way we can declare arr1 G and later build it in DIM::DIM constructor
arr1()
{
}
class DIM:
protected:
arr1<double> G; //I've moved G from the constructor so that PHYS_FIELD can inherit it directly
DIM::DIM()
{
N=10;
G = arr1<double>(N);
for (int i=0; i<N; i++)
G(i)=i;
};
class PHYS_FIELD
remove arr1<double> G; from PHYS_FIELD header so that it doesn't hide the G inherited from DIM
PHYS_FIELD::PHYS_FIELD() { //removed G(N)
cout << " from phys_field.cpp " << endl;
cout << N << endl;
for (int i=0; i<N; i++)
cout << i << " " << G(i) << endl;
};
Is this what you are looking for?

Related

StringBuilder Class in C++ not working properly

I'm working on an assignment to create a class called StringBuilder that is used for fast string concatenation. I'm supposed to store strings in a dynamic array and have methods such as Append(string) which adds a new string to the dynamic array. The method I'm currently struggling with is GetString() that creates a single string on the heap that is the length of all the strings in the dynamic array that have been added thus far.
the code I have so far is:
okay my main problem is my GetString() function prints out hello over and over again until I force quit the program in Xcode. I don't understand what inside that method is making that happen.
My header file:
#pragma once
#include <string>
using namespace std;
class StringBuilder
{
public:
StringBuilder();
//~StringBuilder();
void GetString();
void AppendAll(string*, int);
void Length();
void Clear();
void Append(string userString);
void DoubleArray(string*& allWords, int newCapacity);
private:
string* p_array;
int capacity = 5;
};
my .cpp file :
#include "StringBuilder.hpp"
#include <iostream>
#include <string>
using namespace std;
----------
void StringBuilder::Append(string userString)
{
int nextWordPosition = 0;
for(int i=0; i < capacity ; i++)
{
p_array[i] = userString;
cout << p_array[i] << endl;
nextWordPosition +=1;
if(capacity == nextWordPosition)
{
capacity *=2;
DoubleArray(p_array, capacity * 2);
}
}
nextWordPosition++;
}
void StringBuilder::DoubleArray(string*& allWords, int newCapacity)
{
string* p_temp = new string[newCapacity];
for(int i =0; i < newCapacity / 2; i++)
{
p_temp[i] = allWords[i];
}
delete[] allWords;
allWords = p_temp;
}
void StringBuilder:: GetString()
{
for(int i=0; i < capacity ; i++)
{
cout << p_array[i]<< endl;
}
}
my main.cpp file :
#include <iostream>
#include <string>
#include "StringBuilder.hpp"
using namespace std;
int main()
{
string testString = "hello";
string test = "world!";
StringBuilder Builder1;
Builder1.Append(testString);
Builder1.Append(test);
Builder1.GetString();
return 0;
}

'std::out_of_range' in virtual function

I am trying to access the elements of a virtual function which is declared in Class 1 and then defined in Class 2. I understand that the std :: out_of_range error is a memory access problem, but I don't understand the problem in the code main () to access the values.
When calling the function ** m-> function (t, j) ** I cannot access the elements of * parmem *, but if I directly call the output of the function it works: ** parmem.at (1). gamma **. Here is the code:
Class 1:
#include <armadillo>
#include <iostream>
using namespace std;
using namespace arma;
class Class1
{
public:
mat Y;
struct Par
{
mat gamma;
} par;
std::vector<Par> parmem ;
virtual double function( const int t, const int j ) = 0;
};
Class 2:
class Class2 : public Class1
{
public:
virtual double function( const int t, const int j );
};
double Class2::function( const int t, const int j )
{
cout << parmem.at(t).gamma << endl;
return j+t;
}
main()
int main()
{
mat Y=randu<mat>(3,3);
int t=1;
int j=1;
Class2 *m = new Class2;
std::vector<Class1::Par> parmem {
{Y},
{2*Y}
};
cout << parmem.at(1).gamma << endl; //funciona
cout << m->function(t,j) << endl; //no funciona
return 0;
}
Thanks for the info.
In the following lines, you create independent objects:
Class2 *m = new Class2;
std::vector<Class1::Par> parmem {
{Y},
{2*Y}
};
The std::vector<Class1::Par> parmem {{Y},{2*Y}}; is not part of the instance of the object m is pointing at.
It should work if you assign parmem to the object m points on by adding m->parmem = paramen; to the code.
int main()
{
mat Y=randu<mat>(3,3);
int t=1;
int j=1;
Class2 *m = new Class2;
std::vector<Class1::Par> parmem {
{Y},
{2*Y}
};
m->parmem = paramen;
cout << parmem.at(1).gamma << endl; //funciona
cout << m->function(t,j) << endl; //no funciona
return 0;
}

Return pointer to array virtual template function

I would like to return an array to a pointer, in a virtual function that is a member of a derived class of a template class. In details, my classes definition is:
Sampler.h
#ifndef SAMPLER_H
#define SAMPLER_H
template <class T>
class Sampler
{
public:
virtual T getnumber()=0;
virtual T* simulation(int n)=0;
};
class UniformSampler:public Sampler<double>
{
public:
virtual double getnumber();
virtual double* simulation(int n);
UniformSampler(double a=0.0, double b=1.0);
private:
double low_bound;
double up_bound;
};
#endif
The class Sampler is a template class in order to be able to derive an other sampler with vectors later. The implementation is:
Sampler.cpp
#include "Sampler.h"
#include<iostream>
#include<cstdlib>
#include<cmath>
using namespace std;
//Uniform
UniformSampler::UniformSampler(double a, double b)
{
low_bound=a;
up_bound=b;
}
double UniformSampler::getnumber()
{
int myrand=rand();
while((myrand==0)||(myrand==RAND_MAX)){myrand = rand(); } //We want a number in (0, RAND_MAX).
double myuni = myrand/static_cast<double>(RAND_MAX); //Create a number in (0,1).
return low_bound + myuni*(up_bound-low_bound);
}
double* UniformSampler::simulation(int n){
double simulations[n];
for(int i=0; i<n; i++){
simulations[i] = this->getnumber();
}
return simulations;
}
My problem is that, when I try to call this program in the main(), it looks like the assignment of the pointer doesn't work. Here is my main.cpp:
#include <iostream>
#include <math.h>
#include <cstdlib>
#include <time.h>
using namespace std;
#include "Sampler.h"
int main(){
srand(time(0));
int n=10;
double *unif = new double[n];
UniformSampler uni;
unif = uni.simulation(n);
for ( int i = 0; i < n; i++ ) {
cout << "*(p + " << i << ") : ";
cout << *(unif + i) << endl;
}
delete[] unif;
return 0;
}
When I run it, it doesn't print any of the elements that unif points to. I don't understand what is wrong there.
UniformSampler::simulation is twice wrong:
double simulations[n]; uses VLA extension, so not C++ standard compliant.
you return pointer on local variable, so dangling pointer.
Solution: use std::vector instead.
#include <vector>
template <class T>
class Sampler
{
public:
virtual ~Sampler() = default;
virtual T getnumber() = 0;
virtual std::vector<T> simulation(int n) = 0;
};
class UniformSampler:public Sampler<double>
{
public:
explicit UniformSampler(double a=0.0, double b=1.0);
double getnumber() overrid;
std::vector<double> simulation(int n) override
{
std::vector<double> res(n);
for (auto& val : res){
res = getnumber();
}
return res;
}
private:
double low_bound;
double up_bound;
};
int main(){
srand(time(0));
constexpr int n = 10;
UniformSampler uni;
auto unif = uni.simulation(n);
for (int i = 0; i < n; i++ ) {
std::cout << "p[" << i << "]: " << unif[i] << endl;
}
}

What is the proper way of passing a vector?

Im on year 10 and our teacher wants us to create an original project and using pointers
What I want to do is to create Members and be able to sort the members by there names and print them
When I run my code it says Invalid Access
Team.h
#ifndef TEAM_H
#define TEAM_H
#include "Staff.h"
#include <vector>
#include <iostream>
using std::vector;
class Team: public Staff
{
public:
Team();
~Team();
vector<Staff *> &getVector();
private:
vector<Staff *> myStaffs;
};
#endif // TEAM_H
Team.cpp
Team::Team()
{
for(unsigned int iStaff = 0; iStaff < myStaffs.size(); iStaff++)
{
myStaffs[iStaff] = createStaff(iStaff);
}
}
vector<Staff*>& Team::getVector()
{
return myStaffs;
}
Command class will do the sorting of team and print all team members
Command.cpp
void Command::printStaffs(vector<Staff*>&myStaffs)
{
for(unsigned int iStaff = 0; iStaff < myStaffs.size(); iStaff++)
{
std::cout << "Staff ID number: "<< myStaffs[iStaff]->getStaId() << std::endl
<< "Staff Skills 1: " << *myStaffs[iStaff]->getStaSkill() << std::endl
<< "Staff Skills 2: " << *myStaffs[iStaff]->getStaSkill() << std::endl
<< "Staff Skills 3: " << *myStaffs[iStaff]->getStaSkill() << std::endl
<< std::endl;
}
}
Command.h
#ifndef CommandH
#define CommandH
#include "Team.h"
#include <vector>
#include <iostream>
using std::vector;
class Command: public Team
{
public:
Command(){}
~Command(){}
void sortVector(vector<Staff* >&vectorTemp);
void printStaffs(vector<Staff* >&);
private:
vector<Staff *> vectEmployee;
};
//--------------------------------------------------------------------------
#endif
main.cpp
#include <iostream>
#include <conio.h>
#include "Team.h"
#include "Command.h"
int main()
{
Team t;
Command c;
c.printStaffs(t.getVector());
getch();
return 0;
}
Staff.h
#ifndef STAFF_H
#define STAFF_H
#include <cstdlib>
#include <ctime>
#include <string>
using std::rand;
class Staff
{
public:
Staff();
~Staff();
static Staff* createStaff(int); // creates staffs
int** getStaSkill();
int getStaId(); // returns Staff ID
static int genRanNum(int); //Generate random number
private:
int *staSkill[3];
int staId;
//int staDeptAsigned;
};
#endif
Staff.cpp
#include "Staff.h"
Staff::Staff()
{
*staSkill = new int[3];
}
Staff *Staff::createStaff(int s)
{
Staff *staff = new Staff();
staff->staId = s;
*(staff->staSkill[0]) = genRanNum(10);
*(staff->staSkill[1]) = genRanNum(10);
*(staff->staSkill[2]) = genRanNum(10);
return staff;
}
int** Staff::getStaSkill()
{
return staSkill;
}
int Staff::getStaId()
{
return staId;
}
int Staff::genRanNum(int num)
{
return 1 +(std::rand()%num);
}
Staff::~Staff(){}
When you construct a Team, you have the following constructor:
Team::Team()
{
for(unsigned int iStaff = 0; iStaff < myStaffs.size(); iStaff++)
{
myStaffs[iStaff] = createStaff(iStaff);
}
}
However, myStaffs is a member of Team and gets default constructed as empty, so nothing happens here since myStaffs.size() == 0.
Calling printStaffs on this Team::getVector() will correctly inform you that the vector is empty:
int main()
{
Command c;
Team t; // t.myStaffs will be empty
c.printStaffs(t.getVector()); // passes an empty vector to printStaffs
return 0;
}
You might want to pass a number to your Team constructor to create that many staffs:
Team::Team(int number_of_staff)
{
for(unsigned int iStaff = 0; iStaff < number_of_staff; iStaff++)
{
myStaffs.push_back(createStaff(iStaff));
}
}
int main()
{
Command c;
Team t(5); // t.myStaffs will contain 5 staff members
c.printStaffs(t.getVector()); // passes vector of 5 staff
return 0;
}

Seg Fault with Class Constructors C++

I am new to classes and am having a lot of difficulty with the constructors. I have two constructors for a business class and whenever I attempt to create a business object or do anything with the business object I immediately Seg Fault. The business class interacts with an additional class called Customer. If anyone could offer any help I would greatly appreciate it.
Business.h
#ifndef BUSINESS_H
#define BUSINESS_H
#include <iostream>
#include <string>
#include "customer.h"
using namespace std;
class Business
{
public:
Business();
Business(string name, float cash);
void printData() const;
void addCustomer(Customer newCustomer);
void make_a_sale();
private:
string businessName;
float cashInReg;
string itemArray[10];
Customer custInBus[10];
short numOfItems;
short numOfCustom;
};
#endif
Business.cpp
#include "business.h"
#include <iostream>
#include <cstdlib>
using namespace std;
Business::Business(): businessName("Business"), cashInReg(0), numOfItems(0),
numOfCustom(0) {}
Business::Business(string name, float cash) : businessName(name),
cashInReg(cash), numOfCustom(0) {}
void Business::printData() const
{
cout << businessName <<endl;
for (int i=0; i<numOfCustom; i++)
{
cout << "\t Customer Name: " << custInBus[i].getName() <<endl;
}
for (int i=0; i<numOfItems; i++)
{
cout << "\t Item list: " <<itemArray[i] <<endl;
}
}
void Business::addCustomer(Customer newCustomer)
{
custInBus[numOfCustom-1] = newCustomer;
numOfCustom++;
}
void Business::make_a_sale()
{
int randomItem;
int currCustomer=0;
while (currCustomer < numOfCustom)
{
randomItem = rand() %tempItems;
custInBus[currCustomer].purchase(tempArray[randomItem]);
currCustomer ++;
}
}
void Business::addCustomer(Customer newCustomer)
{
custInBus[numOfCustom] = newCustomer;
//use numOfCustom instead of numOfCustom-1
numOfCustom++;
}