getting size of an array from memberfunction - c++

I'm working on a project where I need to declare a std::array as a private variable in a class, but the size of this array should be returned from a memberfunction called getNumberOfStudents().
Do you have any idea how could I solve this problem?
I will appreciate your help.
class Student{
private:
std::array<int,getNumberOfStudents()> arr;
public:
int getNumberOfStudents(){
std::cout<<"How many students do you wanna add? ";
std::cin>>numberOfStudent;
return numberOfStudent;
}
};

Related

Creating multiple object in other class C++

I made hospital class and patient class, so what I am trying to do is to make Patient[] patients < this. However, there is showing some error error: expected unqualified-id before '[' token
I do not know what it is wrong with that.
Thank you for your response.
class Hospital
{
public:
Hospital();
void determinePatientType();
protected:
private:
Patient[] patients;
char * fileName;
int patientCapacity;
char * hospitalName;
int totalPatients;
};
1- That is not how to declare an array:
Patient[] patients;
You must make the subscript operator after the identifier not before it.
Patient patients[size];
2- You have to specify array size at compile time so:
patient pat[size];
The size must be constant at compile time. If you want a dynamic size then consider using dynamic arrays. Also i recommend using class vector.
To use a dynamic array you should use pointesrs:
patient* patients;
And layer on you can allocate it:
patients = new patient[size];
Your class could look like:
nclude
using namespace std;
class Hospital{
public:
Hospital(int); // constructor
~Hospital(); // destructor
Hospital();
void determinePatientType();
private:
Patient* patients;
char * fileName;
int patientCapacity;
char * hospitalName;
int totalPatients;
};
Hospital::Hospital(int size){
patients = new Patient[size]; // allocating dynamic memory
// some initialization and processing here
}
Hospital::~Hospital(){
delete[] patients; //freeing up memory
}

What is this "*ptrList [100] " inside the class?

Recently, I have seen this code:
class Student; // forward declaration
class Teacher
{
friend void registration(Teacher &t, Student &s);
public:
void setGrades(); // sets students' grades
protected:
int numStudents;
Student *ptrList[100]; // <--- ???
};
That looks like a mixture of pointer and array...
Usually, it is either int *ptr or int array[10]
I have never seen something like this. Can someone explain this to me?
You have an array of pointers to type Student. Think about it this way:
A typical declaration for an array in C++ is:
name [elements];
In the provided example the <type> used for the elements of the array is Student*, which is a pointer to type Student.

Array of Pointers in C++

I'm trying to writing some code for my c++ class. I'm using eclipse. I'm having a hard time trying to understand some of the instructions in the problem.
I've created a base class called Ship and then used inheritance for my CruiseShip class and CargoShip class.
For the CruiseShip class, I'm instructed to create
A print function that overrides the print function in the base class. The CruiseShip
class’s print function should display only the ship’s name and the maximum number
of passengers.
And similarly for the CargoShip class
A print function that overrides the print function in the base class. The CargoShip
class’s print function should display only the ship’s name and the ship’s cargo capacity.
I'm not sure what it means to "override" the print function in the base class.
It also instructs me to
Demonstrate the classes in a program that has an array of Ship pointers. The array
elements should be initialized with the addresses of dynamically allocated Ship ,
CruiseShip , and CargoShip objects. The program should then step through the array, calling
each object’s print function.
#include <iostream>
#include <string>
using namespace std;
class Ship
{
protected:
string ship_name;
int year_built;
public:
Ship()
{
ship_name="";
year_built=0;
}
void set_ship_name(string str)
{
ship_name=str;
}
void set_year(int y)
{
year_built=y;
}
int get_year()
{
return year_built;
}
string get_ship_name()
{
return ship_name;
}
void print(string, int)
{
cout<<"Ship name is "<<ship_name<<" and it was built in the year "<<year_built<<endl;
}
};
class CruiseShip: public Ship
{
private:
int max_passengers;
public:
CruiseShip()// :Ship(str,year)
{
max_passengers=0;
}
void set_passengers(int pass)
{
max_passengers=pass;
}
int get_passengers()
{
return max_passengers;
}
void print1(string, int)
{
cout<<"Ship name is "<<get_ship_name()<<" and max number of passengers are "<<max_passengers<<endl;
}
};
class CargoShip: public Ship
{
private:
int cargo_capacity_in_tons;
public:
CargoShip()//:Ship (str,year)
{
cargo_capacity_in_tons=0;
}
void set_capacity(int pass)
{
cargo_capacity_in_tons=pass;
}
int get_capacity()
{
return cargo_capacity_in_tons;
}
void print2(string, int)
{
cout<<"Ship name is "<<get_ship_name()<<" and its capacity is "<<cargo_capacity_in_tons<<" Tons."<<endl;
}
};
int main(){
CruiseShip ship1;
CargoShip ship2;
string ship_name1;
string ship_name2;
int year_built1;
int year_built2;
int max_passengers;
int cargo_capacity_in_tons;
cout<<"What is the name of the cruise ship?"<<endl;
cin>>ship_name1;
ship1.set_ship_name(ship_name1);
cout<<"What year was "<<ship_name1<<" built in?"<<endl;
cin>>year_built1;
ship1.set_year(year_built1);
cout<<"What is the maximum capacity of "<<ship_name1<<"?"<<endl;
cin>>max_passengers;
ship1.set_passengers(max_passengers);
//ship1.print(ship_name1, year_built1);
ship1.print1(ship_name1, max_passengers);
cout<<"What is the name of the cargo ship?"<<endl;
cin>>ship_name2;
ship2.set_ship_name(ship_name2);
cout<<"What year was "<<ship_name2<<" built in?"<<endl;
cin>>year_built2;
ship2.set_year(year_built2);
cout<<"What is the maximum capacity of "<<ship_name2<<" in tons?"<<endl;
cin>>cargo_capacity_in_tons;
ship2.set_capacity(cargo_capacity_in_tons);
ship2.print2(ship_name2, cargo_capacity_in_tons);
return 0;
}
Let´s say you have the following classes:
class Animal
{
private:
int x;
int y;
public:
virtual string sound() {return "Animal";}
void move() {x += 1; y+=1;}
};
class Cow
{
string sound() {return "Muh"} //this is overriding
string sound(string soundYouWant) {return soundYouWant;} //this is not overriding as string sound(string soundYouWant) is not the same as string sound()
void move() {x += 1; y+=1;} //this is also not overriding as move() in Animal has no virtual
};
So to summarize, overriding means you have a virtual method in the base class and you re-declare it in the derived class. This way, you are able to re-define it for every derived class (the method-body can be different for the base class and each of its derived classes).
Now to dynamic allocated arrays:
int size;
std::cin >> size;
int *array = new int[size]; //the array is stored on the heap
delete[] array; //deallocates the array and so frees the memory
If you create an array on the stack (without new), you either have to hardcode its size using literals (0, 1, 2, ...) or using a const int variableName. This way, the compiler knows the array size during compile time. So you have to know the array size while writing your program. Consequently, the compiler wouldn´t allow you to do this: std::cin >> size;.
Using new (dynamical arrays) you are allowed to specify the array size during compile time. So it is legal to let your program calculate the array size or take it as an user input. With dynamic arrays you also have a lot, lot, lot more memory than using the small stack (stackoverflow).
int *array: obviously the memory content is interpreted as integers. *array points to the first element of the array. int *array does NOT know the SIZE of the array. You have to keep track of that yourself.
new int[size]: You are reserving space for size * integers on the heap.
You might know that C++ does not have a garbage collector. This is when delete[] array; comes into play. When you don´t need array anymore (this includes other pointers pointing to array) you should call delete to free the memory. With small, short running programs, forgetting it won´t matter as the OS (operation system) will free the memory after your program has terminated. Nevertheless, you should use delete as not using it is very bad still and will lead to trouble with bigger programs. You should place delete in the destructor of a class (~clasname()) if you use array within a class.

Why is this giving me error C2661:no overloaded function takes 2 arguments?

error C2661: 'Stock::Stock' : no overloaded function takes 2 arguments
I'm using Visual Studio 2012 fyi and I keep getting a C2661 error every time I try to fill a vector with objects of a class:
void AFTS::createSys() {
AFTS::fs.assign(100, new Stock());
// the error occurs when calling the assign() function
}
Here is the class holding the vector:
class AFTS {
public:
std::vector<Stock> fs;
void createSys();
void addStock(Stock stock, int price);
void deleteStock(Stock stock);
int stockGetPrice(Stock stock);
void sellStock(Stock stock, int price);
void buyStock(Stock stock, int min, int max);
};
Here is the class i'm trying to fill the vector with:
class Stock {
public:
int price;
std::string tick;
};
At first i thought it could be an error related to including header files but i've checked multiple times and they seem to be correct so I can't quite see what i'm doing wrong to cause this.
Stop misusing new. That's for dynamic allocation, not for every "new" object you make.
You have a container of Stock objects, not Stock* pointers, so pushing new Stock into it is incorrect. At best, you'd be creating a vector filled with 100 pointers to the same dynamically-allocated object! C++ ain't Java.
All you need is this:
fs.clear(); // may not need this; depends on prior vector use
fs.resize(100);
Those elements will be default-constructed.
I've also taken the liberty of removing the redundant AFTS:: qualifier.
std::vector<Stock> fs;
Your vector contains Stocks.
AFTS::fs.assign(100, new Stock());
But you try to insert a Stock*.
In any case, one hundred pointers pointing to the same Stock is probably bad.
I believe the problem is that you try to insert a pointer instead of an object:
std::vector<Stock> fs;
You have a simple vector here of object class Stock, so it should be filled like:
AFTS::fs.assign(100, Stock());

Accessing a 2D array between two friend classes

My question is how to access and modify a 2D array defined in one class that is friends with another class. Below are some details on my question:
In class A I declare and allocate the appropriate space for my 2D array (pointer-to-pointer) u.
Class A
{
public:
friend class B;
long double **u;
int fun;
void make();
};
void A::make()
{
long double **u = new long double *[nx];
for (int i=0;i<nx;i++)
u[i] = new long double [ny];
int fun = 9;
}
Class A is friends with Class B; I need to use the array I declared in Class A in a function defined in class B. Below is my Class B:
class B
{
public:
void get(A*);
};
void B::get(A *pt)
{
using namespace std;
cout << pt->fun;
cout << pt->u[0][0];
}
I get a Bus error on my second cout pt->u[0][0]. Is there a simple way to use this setup I have to access my u[][] array? I think that I get the error because the pointer points to the 1st entry of my array, thus my whole 2D array is saved in memory as a single row (thinking aloud here). I'm a Fortran guy so this stuff is a little new to me.
Any help or "pointers" to other helpful threads would be appreciated.
Thank you !
Alberto
I think you get error because A::u is not initialized ( in method A::make you initialize a local variable u, not member. You need to change
void A::make()
{
long double **u = new long double *[nx]; // should be just u, or this->u.
There are some problems with your code: nx and ny don't seem to be defined anywhere, and in make you don't initialize A::fun at all, you instead set a local variable named fun which goes out of scope immediately.
As for your error, it sounds like the error stems from the fact that make() has not been called on pt. Ensure that make() is called on the instance you pass to get, otherwise the array u will not be allocated.