Creating multiple object in other class C++ - 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
}

Related

Declared a structure variable which is a dynamic array of another structure. Why is the following C++ program being crashed?

I have declared a structure variable which is a dynamic array of another structure but the program crashes every time. Where am I doing wrong? What are the necessary steps to be taken? I am using DEVC++.
#include<iostream>
#include<cstdlib>
using namespace std;
struct Project{
int pid;
string name;
};
struct employee{
int eid;
string name;
Project *project_list;
};
int main(){
struct employee e;
e.eid = 123;
e.name = "789";
e.project_list = (Project *)malloc(2 * sizeof(Project));
e.project_list[0].pid = 100;
e.project_list[0].name = "Game";
}
malloc() does not initialize compilcated classes properly and shouldn't be used in C++. You should use new or new[] instead.
e.project_list = new Project[2];
The structure Project uses an object of the type std::string
struct Project{
int pid;
string name;
};
So first of all you need to include the header <string>
#include <string>
To create (and to destroy) an object of this type its constructor (and destructor) shall be called. But the C function malloc knows nothing about constructors. Moreover it even does not initialize the allocated memory.
So in these statements
e.project_list[0].pid = 100;
e.project_list[0].name = "Game";
there is an access to objects of the type std::string that were not created. Their constructors were not called.
Use the operator new instead of malloc
e.project_list = new Project[2];

Struggling with the declaration of class attributes inside the C++ header file?

As a C++ beginner, I oftentimes find myself struggling with the declaration of class attributes inside the header file that need more information than just a name, like arrays and objects of other classes with constructors.
Here's an example
SomeClass.h :
#include "OtherClass.h"
class SomeClass {
int num; // works fine
float arr[]; // produces an error because size is not declared
OtherClass obj; // produces an error because the constructor parameters are not passed in
public:
void setup();
void update();
};
SomeClass.cpp:
#include "SomeClass.h"
void SomeClass::setup() {
num = 10; // easy peasy, works!
arr = float some_arr[5 * num]; // error
// Fill in the array
for (int i = 0; i < 5 * num; i += num) {
ass[i] = 12;
}
// Fill in the class attributes
obj = {120, 40}; // error
}
void SomeClass::update() {
// Update stuff
}
In case of the array arr, how can I declare an array, if I don't know it's size at the moment of the declaration in the header file?
How can class objects with constructors be declared in the header file, without passing in unknown parameters at that moment?
Thanks.
In case of the array arr, how can I declare an array, if I don't know
it's size at the moment of the declaration in the header file?
You can't! C++ does not support variable length arrays, although some compilers (such as GCC) add support for them as an extension.
Instead, you should consider using the std::vector container type, from the Standard Template Library.
In your header/declaration:
class SomeClass {
int num; // works fine
// float arr[]; // produces an error because size is not declared
std::vector<float> arr;
//...
};
And, for your setup() function:
void SomeClass::setup() {
num = 10; // easy peasy, works!
// arr = float some_arr[5 * num]; // error
arr.resize(5 * num); // Sets the size of the container
// Fill in the array...
for (int i = 0; i < 5 * num; i += num) {
arr[i] = 12; // You can access (valid) elements just like a normal array!
}
//...
}
In case you don't know the array size before hand you can use dynamic allocation feature in C++.
First declare your array variable as follow
float *arr;
Then you can allocate required size as follows
arr=new float[10];
To deallocate memory
delete[] arr;
If want to dynamically allocate objects then,Declare class as
ClassName *obj;
Then to allocate use
obj=new ClassName(your_parameters);
Then you can delete it using
delete obj;
TIP:
It is always a good practice make pointer variable NULL after you have de-allocated memory.
Do arr=NULL; and obj=NULL; after de-allocating

Accessing specific attributes of an array of a user defined type

I'm a beginner in C++ and I am trying to create a program which simulates a flight management system. I have created classes to simplify the process. Right now, I have a class named "Flight" which has other user-defined data types as its attributes. For example, it includes two "Date" objects, for arrival and departure dates of my flight object. I also have an array of 30 "Passenger" objects which represent the passengers on my flight. I'm experiencing difficulty making changes to this array though. I need to write a member function for my Flight class which can delete Passengers from the array given the ID (which is an attribute of Passenger).
I want to try to implement this function by passing it an integer "removeID". This value is then compared to the ID's of the passengers in the array. If it matches, the entry is "deleted" essentially freeing the space in the array.
My class Flight is defined as such in its own header file.
#include <string>
#include "Date.h"
#include "Time.h"
#include "Passenger.h"
#ifndef FLIGHT_H_
#define FLIGHT_H_
class Flight
{
public:
Flight(std::string, Date, Date, Time, Time);
float flightTime();
void addPassenger(Passenger);
void removePassenger(int);
bool listChecker(Passenger);
void flightListPrinter()const;
int seatsRemaining();
private:
std::string flightNumber;
Date arrivalDate;
Date departureDate;
Time arrivalTime;
Time departureTime;
std::string destination;
Passenger* passengerList[30];
int numPassengers;
};
#endif
This is the layout of my class Passenger:
#include <string>
#include "Date.h"
class Passenger
{
public:
//Part a)
// Constructor
Passenger(int = 1337, std::string = "Name", std::string = "Banana Island", std::string = "(514)514-5145", Date birth=(1,1,1999));
// Part b)
int getID();
std::string getName();
std::string getAddress();
std::string getTel();
Date getBday();
// Part c)
void setAddress(std::string);
void setTel(std::string);
void setBirthD(Date);
// Part d)
void printInfo()const;
private:
int ID;
std::string name;
std::string address;
std::string Tel;
Date birthD;
};
I'm trying to access the ID, an attribute of the Passenger object, which itself is and attribute of the Flight object. The passengers are all stored in an array called passengerList, it is 30 passengers long. In my main.cpp file, I've defined the remove passenger function as follows:
void Flight::removePassenger(int removeThisID) // Passing the ID to remove
{
for (int i = 0; i < 30; i++) // Check all the passengers in the array
{
// Unsure about the way to access the ID. PassengerList[i].ID == removeThisID ?
}
}
Unfortunately, you can't delete from an array, from what I understand of your project I can suggest you 2 things to overcome this problem
1 - You can store the array in some other data structure in every deletion, and reinitialize it without your target, which is a lot of work OR,
2 - You can use vectors from cpp's standart library (std) which will do the first part for you, automatically. You can check the vectors from http://www.cplusplus.com/reference/vector/vector/vector/
You can not remove from an array. Its fixed size.
One way would be to recreate the array everytime you change the size,
but that would be quite annoying.
Gladly there is the c++ standard library which you can use to solve
such problems.
It has a diverse set of containers that manage the storage space for their elements and provide member functions to access them.
Replace Passenger* passengerList[30] with std::vector<Passenger> passengerList
void Flight::removePassenger(int removeThisID) // Passing the ID to remove
{
for (unsigned int i = 0; i < passengerList.size(); i++)
{
// if (passengerList.at(i).getID() == removeThisID)
if (passengerList[i].getID() == removeThisID)
{
passengerList.erase(passengerList.begin()+i);
return;
}
}
}

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.

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.