I am creating a project , where i am storing pointer to object in vector(STL).
I want to perform operation based on particular parameter of class . but how to use it i am not getting???
void BankingSystem :: Account_info()
{
// Account * mAccount = vobject.back();
long int ACC_NUMBER;
cout << "Enter AccountNumber : " <<endl;
cin >> ACC_NUMBER;
Account * mAccount = std::find(vobject.begin(),vobject.end(),ACC_NUMBER); //finding based on Account number u can use any parameter
cout << mAccount->Acc_holder.firstName << endl;
cout << mAccount->Acc_holder.aadharNo <<endl;
delete mAccount;
}
std::find (and std::find_if) returns an iterator to the found element (or vobject.end() if it's not found).
You could change it like this:
void BankingSystem :: Account_info()
{
long int ACC_NUMBER;
cout << "Enter AccountNumber : " <<endl;
cin >> ACC_NUMBER;
auto mAccount = std::find_if(vobject.begin(), vobject.end(),
[&ACC_NUMBER](const Account* a) {
// acc_number is maybe called something else in
// your Account class.
return a->acc_number == ACC_NUMBER;
});
// check that you actually found something before printing and erasing:
if(mAccount != vobject.end()) {
auto AccountPtr = *mAccount;
cout << AccountPtr->Acc_holder.firstName << endl;
cout << AccountPtr->Acc_holder.aadharNo <<endl;
vobject.erase(mAccount); // not "delete mAccount;"
delete AccountPtr; // if it's actually is supposed to be deleted
}
}
You should however most probably store Account and not Account* in your vector.
I have a class of light bulbs. There are methods and constructors in this class. There is even a destructor) The problem is that I have to determine and display information about class members with type "n" in the TEST() method (LED lamps).
To implement this task, he developed the gettype() method, which returns the type of an object, and, in fact, the TEST() method, which displays information about light bulbs.
The problem is that nothing works for me. I tried a lot of things, but it doesn’t work out for me to implement this task. I'm new to programming (
Code:
#include <iostream>
using namespace std;
class lamp
{
public:
// methods
void TEST(void);
char* gettype (void);
void INIT(void);
void SHOW(void);
// construcrors
lamp();
lamp(const char *t, int powe, const char *c, double cos);
lamp(const lamp & obj);
// destructor
~lamp();
private:
// data
char type[100]; // LED, energy-saving or incandescent lamp
int power; // LED lamp - "n"
char color[100];
double cost;
};
lamp::lamp() {
cout << "This object was created in the default constructor.\n";
strcpy(type, "");
power = 0;
strcpy(color, "");
cost = 0;
}
lamp::lamp(const char *t, int powe, const char *c, double cos) {
cout << "This object was created in the constructor with parameters.\n";
strcpy(type, t); //*t
power = powe;
strcpy(color, c); //*c
cost = cos;
}
lamp::lamp(const lamp & obj) {
cout << "This object was created in the copy constructor.\n";
strcpy(type, obj.type);
power = obj.power;
strcpy(color, obj.color);
cost = obj.cost;
}
lamp::~lamp() {
cout << "Deletion of object by destructor.\n";
}
void lamp::SHOW(void) {
cout << "Lamp Information:\n";
cout << "\nType > " << type;
cout << "\nPower > " << power;
cout << "\nColor > " << color;
cout << "\nCost > " << cost << endl;
}
void lamp::INIT(void) {
cout << "Enter lamp information:\n";
cout << "\nType (if LED, then n) > "; cin >> type;
cout << "\nPower > "; cin >> power;
cout << "\nColor > "; cin >> color;
cout << "\nCost > "; cin >> cost;
}
char* lamp::gettype (void) {
return type;
}
void lamp::TEST(void) {
cout << "\nType > " << type;
cout << "\nPower > " << power;
cout << "\nColor > " << color;
cout << "\nCost > " << cost << endl;
}
void main() {
setlocale(0, "");
// default constructor for 1 class instance
lamp l1;
cout << "Entering data for the first product." << endl;
l1.INIT();
// constructor with parameters for 2 class instances
cout << endl << "Information about the second object: \n";
lamp l2("n", 950, "yellow", 1580);
// copy constructor for the third object
cout << endl << "Information about the third object: \n";
lamp l3(l2);
// Derived information about all the lamps using the method SHOW
l1.SHOW();
l2.SHOW();
l3.SHOW();
// I create an array of two objects using the default constructor
lamp la[2];
I enter data into an array of objects using the method INIT
cout << "Fill an array of objects with 2 elements." << endl;
for(int i = 0; i < 2; i++) {
la[i].INIT();
}
// I output data from an array of objects using the method SHOW
cout << "Showing items." << endl;
for (int i = 0; i < 2; i++) {
la[i].SHOW();
}
// looking for and displaying information about LED lamps
cout << "Search and display information about LED lamps." << endl;
for (int i = 0; i < 3; i++) {
if (la[i].gettype() == "n") {
cout << endl << " lamp number : " << (i + 1) << endl;
la[i].TEST();
cout << endl;
}
}
system("pause");
}
There are several errors in your code:
strcpy is included in <cstring> which is missed. You need to add it in the beginning:
#include <cstring>
main() function should be declared as int main() and you need to add a return statement
int main() {
//YOUR CODE HERE
return 0;
}
You missed a comment sign at line 104
lamp la[2];
//I enter data into an array of objects using the method INIT
cout << "Fill an array of objects with 2 elements." << endl;
After fixed, your code should be able to run.
i have a program that asks for a number of gifts, and then has you input the description, price, and units for it.
i have a function used to display the details here inside it's own cpp file:
void display(const Gift&) {
cout << "Gift Details:" << endl;
cout << "Description: " << gifts.g_description << endl;
cout << "Price: " << gifts.g_price << endl;
cout << "Units: " << gifts.g_units << endl;
}
and here's where i try to call it through another cpp file:
for (int i = 1; i <= numberOfGifts; i++) {
cout << "Gift #" << i << endl;
display(gifts[i]);
cout << endl;
}
i can't seem to figure out how to have it display the first, second, third, and fourth values? it only displays the fourth values 4 times. would greatly appreciate some help
void display(const Gift&) accepts a reference to a Gift as a parameter, but without an identifier (a name) for the parameter the function cannot interact with the parameter.
Instead use void display(const Gift& gift) and then use gift in place of gifts in the function.
Future bug:
Arrays normally are valid between 0 and the array's dimension -1. In
for (int i = 1; i <= numberOfGifts; i++)
i ranges from 1 to numberOfGifts. At the very least this ignores the first, 0th, element of gifts and quite possibly will allow the program to access one past the end of the array. Skipping the first value is a waste of memory, but might be OK. Trying to access a value outside of the array is bad and the results very unpredictable.
For some reason when I create an object of Student in my code the constructor is entered many many times and I am not sure why. I put a cout statement in the constructor and the code below. Any help of why this is happening would be great.
//Student.cpp
Student::Student() {
ID = 0;
name = "name";
cout << "student constructor" << endl;
}
Student::Student(int id, string name) {
ID = id;
name = this->name;
cout << "student con 2" << endl;
}
//part of SortedList.cpp just incase it is needed
template <class ItemType>
SortedList<ItemType>::SortedList() {
cout << "In the default constructor" << endl;
Max_Items = 50;
info = new ItemType[Max_Items];
length = 0;
//SortedList(50);//Using a default value of 50 if no value is specified
}
//Constructor with a parameter given
template <class ItemType>
SortedList<ItemType>::SortedList(int n) {
cout << "in the non default constructor" << endl;
Max_Items = n;
info = new ItemType[Max_Items];
length = 0;
cout << "At the end of the non default constructor" << endl;
}
/The part of the driver where this is called
ifstream inFile;
ofstream outFile;
int ID; //what /below
string name; //these werent here
inFile.open("studcommands.txt");
outFile.open("outFile.txt");
cout << "Before reading commands" << endl;
inFile >> command; // read commands from a text file
cout << "After reading a command" << endl;
SortedList<Student> list;//() was-is here
cout << "List has been made" << endl;
Student StudentObj;
cout << "Starting while loop" << endl;
while(command != "Quit") {...}
//I am also getting a segmentation fault core dump a little after.
UPDATE For some reason however long I make my list, my student constructor is entered that many times meaning say I enter 30 as the length in my list the constructor is entered 30x instead of just creating an array with 30 slots. What could be the reason with this? I feel as If I have heard of this issue in the past.
In the SortedList constructor, you create a new array of the input size of ItemType objects. The elements of this array will be default constructed when the array is being built. That is why your Student constructor is being called size of the array times.
I want to be able to make a battle scene and put it into a function, but every time i try i have to create objects in a different header file, which i then cant call in main. To try to fix this i made the loop in the main function but it says the object calling the method must be modifiable.
//main.cpp
int main()
{
Characters h;//Created using normal constructor
cout << "Character: \n";
h.setAttack(5);
h.getAttack();
h.setDefense(15);
h.getDefense();
Hero Me;
cout << "Hero: \n";
Me.setAttack(10);
Me.getAttack();
Me.setHp(5);
Me.getHp();
Hero::Hero(1,2,3,4);//Created using overloaded constructor
Monsters m;
cout << "Monster: \n";
m.setAttack(20);
m.getAttack();
Monsters::Monsters(5,6,7,8);
//Problem is this this loop! i cant access the member functions for my objects.
//And i want to be able to put this in a function and call it from another file!
do
{
cout << "Attacking!\n";
cout << "Your hp is: " << Me.getHp() << endl;
cout << "The enemy's hp is: "<< m.getHp << endl;
cout << "\nThe monster has attacked you!\n";
cout << "You received " << m.getStrength() << " damage;" << endl;
Me.setHp() -= m.getStrength() ;//It compiles an error, saying its not modifiable
cout << "\nYour hp is now: " << Me.getHp() << endl;
cout << "Enemy hp is: "<< m.getHp << endl;
cout << "\nNow you attacked!\nYou have dealt "<< Me.getAttack() << " Damage" << endl;
m.setHp() -= Me.getAttack();
cout << "Enemy hp is now: " << m.getHp() - Me.getAttack() << endl;
}while ((Me.getHp() >= 0) && (m.getHp() >= 0));
if ((Me.getHp > 0) && (m.getHp < 0))
cout <<"Congratulations! You killed the enemy!" << endl;
else if ((Me.getHp < 0) && (m.getHp > 0))
cout << "You have died!" << endl;
cin.sync();
cin.get();
return 0;
}
//Here's the rest of my code.
//Hero.h
class Hero:
public Characters
{
public:
Hero();
Hero(int, int, int, int);
~Hero(void);
};
//Hero.cpp
int Herolevel;
int HeroHp;
int HeroStrength;
int HeroAttack;
int HeroDefense;
Hero::Hero()
{
cout << "HOLA! Hero Created using normal constructor\n";
}
Hero::Hero(int newHp, int newLevel, int newAttack, int newDef)
{
cout << "Hero created using Overloaded function!\n";
HeroHp = newHp;
cout << "Hp is: "<< HeroHp << endl;
Herolevel = newLevel;
cout << "level is: " << Herolevel << endl;
HeroAttack = newAttack;
cout << "Attack is: " << HeroAttack << endl;
HeroDefense = newDef;
cout << "Defense is: " << HeroDefense << endl;
}
Hero::~Hero(void)
{
cout << "Hero destroyed!\n";
}
//Monsters.h
#pragma once
#include "Hero.h"
#include "Characters.h"
class Monsters:
public Characters //Hero
{
public:
Monsters(void);
Monsters(int, int, int, int);
//Monsters(int);
~Monsters(void);
};
//Monsters.cpp
int Monsterlevel;
int MonsterHp;
int MonsterStrength;
int MonsterAttack;
int MonsterDefense;
Monsters::Monsters(void)
{
"Monster Created";
}
Monsters::Monsters(int newHp, int newLevel, int newAttack, int newDef)
{
cout << "Monster created using Overloaded function!\n";
MonsterHp = newHp;
cout << "Hp is: "<< MonsterHp << endl;
Monsterlevel = newLevel;
cout << "level is: " << Monsterlevel << endl;
MonsterAttack = newAttack;
cout << "Attack is: " << MonsterAttack << endl;
MonsterDefense = newDef;
cout << "Defense is: " << MonsterDefense << endl;
}
Monsters::~Monsters(void)
{
cout << "\nMonster Destroyed";
}
//Characters.h
#pragma once
class Characters
{
private:
int level;
int Hp;
int Strength;
int Attack;
int Defense;
public:
Characters(void);
Characters(int);
Characters(int, int, int, int);
~Characters(void);
int getAttack();
int getDefense();
int getStrength();
int getHp();
int getLevel();
void setAttack(int);
void setDefense(int);
void setStrength(int);
void setHp(int);
void setlevel(int);
};
//Characters.cpp
Characters::Characters(void)
{
cout << "\nCharacter has been created!\n";
}
Characters::Characters(int random)//How can i make this work?
{
cout << "Level " << level << " character created with: \n";
/*srand ((unsigned)time(0));
random = rand() % 10 + 1;
setlevel(int random);*/
level = random;
}
Characters::~Characters(void)
{
cout << "Character has been destroyed!\n";
}
void Characters::setAttack(int att)//get Character left over hp
{
Attack = att;
}
void Characters::setDefense(int def)//get Character left over hp
{
Defense = def;
}
void Characters::setStrength(int str)//get Character left over hp
{
Strength = str;
}
void Characters::setHp(int damage)//get Character left over hp
{
Hp -= damage;
}
void Characters::setlevel(int lvl)//get Character left over hp
{
level = lvl;
}
int Characters::getAttack()
{
cout << "Your attack is: " << Attack << endl;
return Attack;
}
int Characters::getDefense()
{
cout << "Your defense is: " << Defense << endl;
return Defense;
}
int Characters::getStrength()
{
cout << "Your strength is: " << Strength << endl;
return Strength;
}
int Characters::getHp()
{
cout << "Your hp is: " << Hp << endl;
return Hp;
}
int Characters::getLevel()
{
cout << "Your level is: " << level << endl;
return level;
}
To start with, don't declare the variables global, declare them as member variables! When you declare a global variable, there will be only one instance of that variable in your program, so if you create (for example) two Monster object both will be using the same global variables.
You also don't create any monsters except one, m. The second time you call the Monster constructor you don't create a new Monster object, just call its constructor. After you make the variables member variables (by simply declaring them in the class) you can use the non-default constructor like this:
Monster m; // Uses default constructor
Monster m2(5, 6, 7, 8); // Uses the other constructor
As for the problem you have, it's that getHp method only returns a copy of the hitpoints, and so the statement doesn't actually do anything (it modifies the returned copy, then throw it away). Instead you should call the setHp method:
Me.setHp(Me.getHp() - m.getStrength());
There seems to be a disconnect with how you are understanding OOP (object oriented programming) and C++ programming.
In C++ (and C), you must declare everything before you use it. So if you have a class that you need to use, you must declare it first. Otherwise you will get an error.
In OOP programming, an object is an instance of a class definition. A class has several key components, though not all may be present:
Has a constructor:
This sets up the initial state of any new instance of the class and usually allocates resources used by the object.
Has a destructor:
This deallocates resources used by the object.
Has member variables:
This is how the resources or other state information are attached to the object.
Has member functions:
This is how you operate on the object.
Inherits from another class/struct:
This states an is-a relationship with another class/struct type. I.e. A car is-a vehicle, a bike is-a vehicle. Thus car and bike inherits from vehicle.
Now, your Hero.h file contains the class declaration Hero indicating it's constructors and destructor (BTW, you don't need the (void). That is old C style. In C++ an empty parameter list like () is equivalent to (void).), but it doesn't contain any member variables or functions. This is because you have inherited from Characters. Except that you have not declared Characters before you are using it as a base class. So in your Hero.h file, you must state #include "Character.h" before the declaration of the class. This goes for each header file.
BUT you should also have a guard around the contents of your header in case you include that file multiple times. To do that put something like this around the contents of Hero.h.
#if defined HERO_H
# define HERO_H
... the contents of Hero.h ...
#endif
Do this for each of you header files. Use a UNIQUE guard name for each file. I.e. don't use HERO_H for your Character.h file. NOTE I just noticed you are using #pragma once. This is equivalent to using the guard but is not portable across all compilers.
Going into your Hero.cpp file, there are a few things wrong.
You need to include the Hero.h file.
Remember that C++ is declare before use and each source file is compiled separately. Therefore you must declare everything that is used by each source file before you use it. Since the Hero class is declared in the Hero.h header file, you must include that header file.
Global variables:
I see you are using global variables. Don't do that, not when you have member variables that are supposed to do the same thing. A member variable is part of every instance of that class. In other words, every time you create an instance of the class, you will have a unique memory storage location for that member variable allowing you to have multiple instances that will have different states which don't conflict with each other. I.e.:
Hero::Hero(int newHp, int newLevel, int newAttack, int newDef)
{
cout << "Hero created using Overloaded function!\n";
Hp = newHp;
cout << "Hp is: "<< Hp << endl;
level = newLevel;
cout << "level is: " << level << endl;
Attack = newAttack;
cout << "Attack is: " << Attack << endl;
Defense = newDef;
cout << "Defense is: " << Defense << endl;
}
You also have a default constructor (it not called a 'normal' constructor) for Hero. Why? What is the point of having this? If there is a point, what are the defaults that need to be set for it? Looking at the Character class, I see that you also have not initialised the member variables for the instance either when you call its default constructor. I think the problem you are having here is that you don't know how to initialise an object which inherits from another, which is reasonable since it's not immediately obvious. Look at my last code fragment, and compare it to this new one:
Hero::Hero(int newHp, int newLevel, int newAttack, int newDef)
: Character(newHp, newLevel, newAttack, newDef) // <== initialiser list
{
cout << "Hero created using Overloaded function!\n";
cout << "Hp is: "<< Hp << endl;
cout << "level is: " << level << endl;
cout << "Attack is: " << Attack << endl;
cout << "Defense is: " << Defense << endl;
}
By using the initialiser list, I am initialising the base object by calling it's constructor that takes parameters. Doing it this way removes the need to have a base class that must have a default constructor or you can use the default constructor to generate the random values that you are looking for when calling its constructor that takes a single int value, thus removing the need for that constructor. For a description on how to use the rand() function, see here.
An initialiser list is just that, a list used to initialise the object. Thus it can contain multiple things (hence why it's called a list). The other things it can contain are initial values of member variables.
Characters::Characters(int newHp, int newLevel, int newAttack, int newDef)
: Hp(newHp), level(newLevel) //... etc
{
}
These need to be in the order of base class initialiser (like in the Hero example) and then the member variables in the order that they appear in the class declaration. Some compilers will allow this to be in any order, but again, this is not portable and may result in unexpected behaviour.
Oh, one other thing I noticed is that your Monster.h file includes Hero.h. Why? Does the Monster.h file use an instance of Hero? No. So get rid of it.