Using a user defined class vector inside the class file - c++

I have a class called Account with below parameters:
Account::Account(string ibanCode, string paramOwner, double amount) {}
I have created a vector consisting of class Accounts inside main function:
accs.push_back(Account(fullName, iban, value));
I want to write a function to print all the Account values in my vector by a class member function called displayAll() , and so far I tried this:
void Account::displayAll()
{
for (int i = 0; i < accs.size(); i++)
{
cout << accs[i].displayBalance() << endl;;
}
}
And I want to write it inside the class file. Do you have any suggestions?

I think making it a member would be extremely complicated, the best option should be using a normal function that can access the parameters.
#include <iostream>
#include <vector>
using namespace std;
struct Account {
Account (string ibanCode, string paramOwner, double amount) : _amount(amount), _ibanCode(ibanCode), _paramOwner(paramOwner) {};
string _ibanCode;
string _paramOwner;
double _amount;
};
void DisplayAll (const vector<Account>& Accs) {
for (const auto& Acc : Accs) {
cout << Acc._ibanCode<<' '<<Acc._paramOwner<<' '<< Acc._amount<<'\n';
}
return;
}
int main () {
vector<Account> Accs;
Accs.push_back(Account("SomeCode", "SomeOwner", 2.0));
Accs.push_back(Account("SomeOtherCode", "SomeOtherOwner", 3000.42));
DisplayAll(Accs);
}
To avoid complicating the answer too much I made a struct but you can either make the DisplayAll function a friend of the class or make some getters.

Related

Classes: Instantiating Object Confusion

Below is code for a simple book list with a class to store book names and isbn numbers into an overloaded function using a vector. This program runs fine and I can test it by returning a specific name (or isbn) using an accessor function from my class.
Question: I tried calling (instantiating?) a constructor with parameters from my class but it would not work, so I commented it out. Yet I was still able to run the program without error. From my main below - //BookData bkDataObj(bookName, isbn);
From watching tutorials, I thought I always had to make an object for a specific constructor from a class that I needed to call? My program definitely still uses my overloaded constructor and function declaration BookData(string, int); without making an object for it in main first.
Thanks for any help or input on this matter.
Main
#include <iostream>
#include <string>
#include <vector>
#include "BookData.h"
using namespace std;
int main()
{
string bookName[] = { "Neuromancer", "The Expanse", "Do Androids Dream of Electric Sheep?", "DUNE" };
int isbn[] = { 345404475, 441569595, 316129089, 441172717 };
//BookData bkDataObj(bookName, isbn); //how did program run without instantiating object for class?
vector <BookData> bookDataArr;
int arrayLength = sizeof(bookName) / sizeof(string);
for (int i = 0; i < arrayLength; i++) {
bookDataArr.push_back(BookData(bookName[i], isbn[i]));
}
cout << "Book 4 is: " << bookDataArr[3].getBookNameCl(); //test if works
return 0;
}
BookData.h
#include <iostream>
#include <string>
using namespace std;
class BookData
{
public:
BookData();
BookData(string, int); //wasn't I supposed to make an object for this constructor in my main?
string getBookNameCl();
int getIsbnCl();
private:
string bookNameCl;
int isbnCl;
};
BookData.cpp
#include "BookData.h"
BookData::BookData() {
bookNameCl = " ";
isbnCl = 0;
}
BookData::BookData(string bookNameOL, int isbnOL) { //how did I use this function
bookNameCl = bookNameOL; //definition without an object in main?
isbnCl = isbnOL;
}
string BookData::getBookNameCl() { //can still return a book name
return bookNameCl;
}
int BookData::getIsbnCl() {
return isbnCl;
}

C++ How to get a specific object in a class

I want to get a specific object in a class in C++. I looked into multiple sites and it seems my question is unique. Okay here's my code.
In House.h
#include <string>
using namespace std;
class House
{
string Name;
int Health;
public:
House(string a, int h);
void GetHouseStats();
void DamageHouse(int d);
~House();
};
in House.cpp
#include "House.h"
#include <iostream>
House::House(string a, int h)
{
Name = a;
Health = h;
}
void House::DamageHouse(int d) {
Health -= d;
cout << "Your " << Name << " has " << Health << " left."<<endl;
}
void House::GetHouseStats() {
cout << Name<<endl;
cout << Health;
}
House::~House()
{
}
in Source.cpp
#include <iostream>
#include "House.h"
using namespace std;
int main()
{
House Kubo("Bahay Kubo", 2);
Kubo.DamageHouse(1);
}
I have House Kubo as my first object. I would like to save the person's houses into a file but my problem is How can I pass the object's name into the function so that save its data into a file? I can manually place the Kubo and do so as
PlayerHouse = Kubo.Name;
But what if I don't know which house I should save? Like instead of typing down
PlayerHouse = Apartment.Name;//2nd house
PlayerHouse = Modern.Name;//3rd house
Can I use an function argument to place the object's name into PlayerHouse? Like this
void SetHouseName(type object){
PlayerHouse = object.Name;
}
Few ways in which this can be done .. is keeping all created object in a container and then access access the container to get the object in and pass it a function which will write it to a file .
Also if you do not want to maintain the container what you have mentioned about using the function will also work fine
Of course, but if you are going to save the Name of the house anyway, why don't you just ask for a std::string in the first place and then pass the Name to that function?
void SetHouseName(std::string name)
{
PlayerHouse = name;
}
If this is outside your House class you need to create a method to expose the Name member of House though, or just make it public.
To answer your initial question, just as how you would pass built-in types, you can do the same for your House type :
void SetHouseName(House house)
{
PlayerHouse = house.Name;
}

Structure Arrays & Pointers

I have to use a struct array called Robot_parts[] for each part_rect struct (part_num, part_name, part_quantity, part_cost)
And through the void display function, I have to display Robot_parts[] array entirely through pointer but I don't know how, and I don't know where to declare Robot_parts[] and whether i have to put any number value inside the brackets.
So far I have:
#include <iostream>
#include <string>
using namespace std;
void display();
struct part_rec
{
int part_num;
string part_name;
int part_quantity;
double part_cost;
};
int main()
{
part_rec Robot_parts[ ] = {
{7789, "QTI", 4, 12.95},
{1654, "bolt", 4, 0.34},
{6931, "nut", 4, 0.25}
};
return 0;
}
void display()
{
cout<<Robot_parts[]<<endl<<endl;
}
If I also made a few other errors, please let me know. Thanks!
As stated in a comment it would be much better to use a c++ container like a std::vector or std::array.
But since your professor requires an old-style array, you could try like the code below - see the comments for explanation:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct part_rec
{
int part_num;
string part_name;
int part_quantity;
double part_cost;
};
// You have to pass a pointer (to the array) and the size of the array
// to the display function
void display(part_rec* Robot_parts, int n);
// Make a function so that you can "cout" your class directly using <<
// Note: Thanks to #BaumMitAugen who provided this comment and link:
// It makes use of the so called Operator Overloading - see:
// https://stackoverflow.com/questions/4421706/operator-overloading
// The link is also below the code section
std::ostream &operator<<(std::ostream &os, part_rec const &m)
{
// Note - Only two members printed here - just add the rest your self
return os << m.part_num << " " << m.part_name;
}
int main()
{
part_rec Robot_parts[] {
{7789, "QTI", 4, 12.95},
{1654, "bolt", 4, 0.34},
{6931, "nut", 4, 0.25}
};
display(Robot_parts, 3);
return 0;
}
void display(part_rec* Robot_parts, int n)
{
// Loop over all instances of your class in the array
for (int i = 0; i < n; ++i)
{
// Print your class
cout << Robot_parts[i] << endl;
}
}
The link recommended by #BaumMitAugen:
Operator overloading

Friend Function accessing private variables

I wrote a small piece of code to test friend functions. It worked fine for methods that didn't belong to a specific class but when I tried to put it into a class all it can access is the public variables (just as any object would).
#include <iostream>
#include <conio.h>
using namespace std;
class something{
int ip = 100;
public:
int x = 100;
void getIP();
friend void cIP::changeIP(something);
};
void something::getIP(){
cout << ip << endl;
}
class cIP{
public:
int i;
cIP();
cIP(int nIP);
something some;
void changeIP(something s);
};
cIP::cIP(){
i = 100;
}
cIP::cIP(int nIP){
i = nIP;
}
void cIP::changeIP(something s){
s.ip = i;
}
s.ip brings up the error member is inaccessible.

Multilevel inheritance/polymorphism and virtual function

I have a multilevel inheritance (from Ship class -> MedicShip class -> Medic class) with virtual function code as below. I suppose the result should be :
Medic 10
Medic 10
But it generated strange result. On the other hand, if I only use one level inheritance (from Ship class -> Medic class without MedicShip class in between) the result will be OK. Could you find my mistake please? Many thank....
#ifndef FLEET_H
#define FLEET_H
#include <string>
#include <vector>
using namespace std;
class Ship
{
public:
Ship(){};
~Ship(){};
int weight;
string typeName;
int getWeight() const;
virtual string getTypeName() const = 0;
};
class MedicShip: public Ship
{
public:
MedicShip(){};
~MedicShip(){};
string getTypeName() const;
};
class Medic: public MedicShip
{
public:
Medic();
};
class Fleet
{
public:
Fleet(){};
vector<Ship*> ships;
vector<Ship*> shipList() const;
};
#endif // FLEET_H
#include "Fleet.h"
#include <iostream>
using namespace std;
vector<Ship*> Fleet::shipList() const
{
return ships;
}
int Ship::getWeight() const
{
return weight;
}
string Ship::getTypeName() const
{
return typeName;
}
string MedicShip::getTypeName() const
{
return typeName;
}
Medic::Medic()
{
weight = 10;
typeName = "Medic";
}
int main()
{
Fleet fleet;
MedicShip newMedic;
fleet.ships.push_back(&newMedic);
fleet.ships.push_back(&newMedic);
for (int j=0; j< fleet.shipList().size(); ++j)
{
Ship* s = fleet.shipList().at(j);
cout << s->getTypeName() << "\t" << s->getWeight() << endl;
}
cin.get();
return 0;
}
You haven't created any instances of class Medic. Did you mean to say
Medic newMedic;
instead of
MedicShip newMedic;
perhaps? So, the Medic constructor isn't being called and weight and typeName aren't being initialized.
~Ship(){};
The first mistake is right here. This destructor should be virtual if you want to delete derived class objects through base class pointer.