Trying to make an array of objects in C++ - c++

I'm having a tough time creating a an array that holds objects of a class I made. I cannot use std::vector to hold the objects so here is what I tried to do:
This is my cpp file:
Resistor.cpp:
#include "Resistor.h"
Resistor::Resistor(int rIndex_, string name_, double resistance_){
int rIndex = rIndex_;
name = name_;
resistance = resistance_;
}
I'm trying to make an array of these Resistor objects in another cpp file:
Rparser.cpp:
#include "Resistor.h"
#include "Node.h"
#include "Rparser.h"
Rparser::Rparser(int maxNodes_, int maxResistors_){
maxNodes = maxNodes_;
maxResistors = maxResistors_;
resistorArray = new Resistor[maxResistors_]; //trying to make an array
}
My Rparser.h file looks like this, as you can see I declared a pointer that points to Resistor datatype:
#include "Resistor.h"
#include "Node.h"
class Rparser{
public:
int maxNodes;
int maxResistors;
Resistor *resistorArray; //declared a pointer here
Rparser(int maxNodes_, int maxResistors_);
~Rparser(){};
I'm getting the following errors:
error: no matching function for call to ‘Resistor::Resistor()’
note: candidates are: Resistor::Resistor(int, std::string, double, int*)
note: Resistor::Resistor(const Resistor&)
Why is it treating the line resistorArray = new Resistor[maxResistors]
as a function call instead of creating an array?

You need a Resistor constructor that takes no arguments (that is what the compiler is telling you in the error message, it is not a function call, but a call to the no arguments constructor.). Think about it, new Resistor[] specifies no constructor arguments.

Related

Passing array of class objects to a function

Passing an array of objects to a function is not giving back the desired values set in the settingUp function.
Try to print the values stored in the first item of the array in the main function.
main.ccp:
//** Libraries included **//
using namespace std;
//#include "common.h"
#include "settingUp.h"
int main(){
statusClass status[5];
//** Main Functions **//
settingUp(status);
status[1].printValues();
}
settings.h:
#ifndef settingUp_h
#define settingUp_h
//** Libraries **//
#include "statusClass.h"
#include <stdio.h>
#include "dataClass.h"
void settingUp(statusClass *_status);
#endif
settings.ccp //UPDATE: few lines corrected!
//** Libraries **//
#include "settingUp.h"
//** Status classes and their functions **//
void settingUp(statusClass *_status){
//statusClass statusProv;
dataClass * prueba0 = new dataClass(); //Corrected!
dataClass * prueba1 = new dataClass(); //Corrected!
dataClass * prueba2 = new dataClass(); //Corrected!
const dataClass * arrayPrueba[3];
prueba0.setValues(1);
prueba1.setValues(2);
prueba2.setValues(3);
arrayPrueba[0] = prueba0; //Corrected!
arrayPrueba[1] = prueba1; //Corrected!
arrayPrueba[2] = prueba2; //Corrected!
_status[1].setValues(1, arrayPrueba);
//_status = &statusProv;
_status[0].printValues();
}
UPDATE:
statusClass.cpp:
//** Libraries **//
#include "statusClass.h"
//** Status classes and their functions **//
void statusClass::setValues (uint8_t _statusSelectorByte, const dataClass **_array){
newStatusSelectorByte = _statusSelectorByte;
array = _array;
};
void statusClass::printValues(){
printf("TP: statusClass -> printValues: Prueba = %d\n", newStatusSelectorByte);
printf("TP: statusClass -> printValues: arrayPrueba = %d\n", array[1]->length);
}
printValues() in the settingUp() gives the right values, not in main.cpp.
Update: for array[0]->length works, for array[2]->length does not work.
When you do the following:
dataClass prueba0;
you create an object on the stack. This object is valid until you exit that function.
One solution is to allocate that object:
dataClass * prueba0 = new dataClass();
That means at some point you'll need to delete the object with:
delete prueba0;
To avoid having to use delete, you should look into using shared pointers.
I think your next problem is that in main you have:
statusClass status[5];
So 5 different status objects.
Then inside the initialization function, you specifically initialize _status[1]:
_status[1].setValues(1, arrayPrueba);
In other words, your _status[0] access within the initialization is going to show the random values that were on the stack when entering main() (which by luck are zeroes by default).
Maybe you are thinking that:
array = _array;
copies the values from one array to another. Right now, all that does is save a pointer. The array on the left is the pointer you created named arrayPrueba.
I just don't think you understand your code much and to tell you the truth, you should be using std::vector instead of C arrays. If you really want to write C++ code, learn the standard library (STL).

C++ Vectors with pre-determined size throwing compile errors

I am very new to C++ and trying to create a simple Student class with a vector of scores of type int.
Here's my class:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <fstream>
#include <sstream>
using namespace std;
class Student {
string last;
string first;
vector<int> scores(10);
public:
Student():last(""), first("") {}
Student(string l, string f) {
last = l;
first = f;
}
~Student() {
last = "";
first = "";
}
Student(Student& s) {
last = s.last;
first = s.first;
scores = s.scores;
}
Student& operator = (Student& s) {
last = s.last;
first = s.first;
scores = s.scores;
return *this;
}
void addScore(int n) {
scores.push_back(n);
}
};
For some reason, I'm getting multiple reference to non-static member function must be called; did you mean to call it with no arguments in reference to the vector scores.
Here's my full list of errors:
main.cpp:15:22: error: expected parameter declarator
vector<int> scores(10);
main.cpp:15:22: error: expected ')'
main.cpp:15:21: note: to match this '('
vector<int> scores(10);
main.cpp:30:4: error: reference to non-static member function must be called; did you mean to call it with no arguments?
scores = s.scores;
main.cpp:35:4: error: reference to non-static member function must be called; did you mean to call it with no arguments?
scores = s.scores;
main.cpp:35:15: error: reference to non-static member function must be called; did you mean to call it with no arguments?
scores = s.scores;
main.cpp:40:4: error: reference to non-static member function must be called; did you mean to call it with no arguments?
scores.push_back(n);
I've tried many things but still have no idea where these errors are coming from. I'm very new to C++, so please forgive me. Any help would be appreciated.
You can't initialize a data member like this:
vector<int> scores(10);
You need one of these forms instead:
vector<int> scores = vector<int>(10);
vector<int> scores = vector<int>{10};
vector<int> scores{vector<int>(10)};
The reason is to avoid initializations that could look like function declarations. Note that this is syntactically valid:
vector<int>{10};
but it initializes the vector to have size 1, with a single element with value 10.
You can't call a constructor in member definition of your class; you need to call it from the initialiser list:
class Student {
string last;
string first;
vector<int> scores;
public:
Student():last(""), first(""), scores(10) {}
Edit At least this was the way pre c++11...
You should use initialization list for this case:
Student():scores(10) {}
What is the reason to create vector with 10 elements if you use push_back() next in the code ?
void addScore(int n) {
scores.push_back(n);
}
This code adds 11th element to the vector. Is it the correct behavior for your project?

incomplete type is not allowed while trying to create an array of pointers

I created 2 classes, Branch and Account and I want my Branch class have an array of Account pointers, but i fail to do it. It says that "incomplete type is not allowed". What is wrong with my code?
#include <string>
#include "Account.h"
using namespace std;
class Branch{
/*--------------------public variables--------------*/
public:
Branch(int id, string name);
Branch(Branch &br);
~Branch();
Account* ownedAccounts[]; // error at this line
string getName();
int getId();
int numberOfBranches;
/*--------------------public variables--------------*/
/*--------------------private variables--------------*/
private:
int branchId;
string branchName;
/*--------------------private variables--------------*/
};
Although you can create an array of pointers to forward-declared classes, you cannot create an array with an unknown size. If you want to create the array at runtime, make a pointer to a pointer (which is of course also allowed):
Account **ownedAccounts;
...
// Later on, in the constructor
ownedAccounts = new Account*[numOwnedAccounts];
...
// Later on, in the destructor
delete[] ownedAccounts;
You need to specify the size of the array... You can't just leave the brackets hanging like that without anything inside them.

Error when changing a vector value in a class

I am attempting to change a value in a vector which is a variable in a class using a function of a class. When I compile, i get the following errors pointing to the "check[c] = cval;" line:
error C3867: 'acc::check': function call missing argument list; use '&acc::check' to create a pointer to member
error C2109: subscript requires array or pointer type
Note: I have already initialized C to be 0 elsewhere in the program. It might be throwing an error because I am giving the address a variable instead of an integer, but when I substitute the variable with an integer, I still get the same errors.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
class acc
{
public:
void add_Cval(double cval);
private:
vector<double> check(); //vector of all checks
int c; //loop marker for cvals
};
void acc::add_Cval(double cval)
{
check[c] = cval;
c++;
}
vector<double> check(); isn't what you think it is. You just declared a function named check that returns a vector<double>. Get rid of the parenthesis like so vector<double> check;.
Also, your vector<double> is empty, you need to give it some space if you want to do check[c] = cval; (or use check.push_back(cval); instead), allocate the space in the constructor (use "initialization lists" as that is what they are for):
Example:
acc(int vecsize) : check(vecsize), c(0) {}
You might also want to make sure check[c] is a valid position in the vector before assigning anything to it.
check is a method, not a data member, so you need to invoke it - check().
void acc::add_Cval(double cval)
{
check()[c] = cval;
c++;
}
or make it a data member:
class acc
{
public:
void add_Cval(double cval);
private:
vector<double> check; //vector of all checks
int c; //loop marker for cvals
};
The compiler is looking for a function called check() that returns a vector of type double.
private:
vector<double> check(); // A private function that returns a vector of type <double>
Needs to be:
private:
vector<double> check; // A private data member

passing vector to function c++

I have a main.cpp test.h and test.cpp> I am trying to pass my vector through so i can use it in test.cpp but i keep getting errors.
//file: main.cpp
int main(){
vector <Item *> s;
//loading my file and assign s[i]->name and s[i]-address
tester(s);
}
//file: test.h
#ifndef TEST_H
#define TEST_H
struct Item{
string name;
string address;
};
#endif
//file: test.cpp
int tester(Item *s[]){
for (i=0; i<s.sizeof();i++){
cout<< s[i]->name<<" "<< s[i]->address<<endl;
}
return 0;
}
---------------errors--------
In file included from main.cpp:13:
test.h:5: error: âstringâ does not name a type
test.h:6: error: âstringâ does not name a type
main.cpp: In function âint main()â:
main.cpp:28: error: cannot convert âstd::vector<Item*, std::allocator<Item*> >â to âItem**â for argument â1â to âint tester(Item**)â
A std::vector<T> and T* [] are not compatible types.
Change your tester() function signature as follows:
//file: test.cpp
int tester(const std::vector<Item>& s) // take a const-reference to the std::vector
// since you don't need to change the values
// in this function
{
for (size_t i = 0; i < s.size(); ++i){
cout<< s[i]->name<<" "<< s[i]->address<<endl;
}
return 0;
}
There are several ways you could pass this std::vector<T> and all have slightly different meanings:
// This would create a COPY of the vector
// that would be local to this function's scope
void tester(std::vector<Item*>);
// This would use a reference to the vector
// this reference could be modified in the
// tester function
// This does NOT involve a second copy of the vector
void tester(std::vector<Item*>&);
// This would use a const-reference to the vector
// this reference could NOT be modified in the
// tester function
// This does NOT involve a second copy of the vector
void tester(const std::vector<Item*>&);
// This would use a pointer to the vector
// This does NOT involve a second copy of the vector
// caveat: use of raw pointers can be dangerous and
// should be avoided for non-trivial cases if possible
void tester(std::vector<Item*>*);
Pass it as std::vector<Item *> & (reference to vector) and use iterator to iterate through it.
You should #include <string>.
string name should read std::string name etc. Same goes for std::vector.
You're calling tester() with a vector, yet it expects an array (the two are not interchangeable).
s.sizeof() is incorrect for both an array and a vector; for the latter, use s.size() or, better yet, use an iterator.
These are just the errors that immediately jump out; there may be more.
A vector is not an array.
int tester(vector<Item *> &s)
(pass as a reference to avoid copying or if you need to modify)
You also need to modify your code inside the tester function to work correctly as a vector.
You should fix
test.h:5: error: âstringâ does not name a type
first, probably by using namespace std; and #include <string>
You are missing includes
#include <string>
#include <vector>
and you need to use std::string and std::vector<>. A std::vector is not an array, so you should pass the vector as reference
int tester(std::vector<Item*> & vec) { //... }
or even as const std::vector<Item*> & if you are not going to modify the passed vector.
Also, are you sure, that you'll need a vector of pointers? What are you trying to achieve?