I am new to using pointers with c++, so I am trying this small code but the problem is that when i try to print name i get this random weird number \364\277\357\376\326\241+\310\364\277\357\376\310. This is not the memory address, which is confusing and what confuses me more that when i replace name with getName() it works perfectly and prints the name! Thanks you!!
Person.cpp
#include "Pesron.hpp"
#include <string>
#include <iostream>
using namespace std;
Person:: Person()
{
}
Person::Person(string Name, int Age)
{
name=&Name;
age=Age;
}
void Person:: setName(string Name)
{
name=&Name;
}
void Person:: setAge(int Age)
{
age=Age;
}
string Person:: getName()
{
return *name;
}
int Person:: getAge()
{
return age;
}
void Person:: display()
{
cout<<*name<<" "<<age<<" ";
}
Person::~Person()
{
}
Student.cpp
#include "Student.hpp"
Student:: Student(string Name, int Age,int Grades, int ID):Person(Name , Age)
{
grades=Grades;
id=ID;
}
void Student:: setId(int ID)
{
id=ID;
}
int Student:: getId()
{
return id;
}
void Student:: setGrades(int Grades )
{
grades= Grades;
}
int Student:: getGrades()
{
return grades;
}
void Student:: display()
{
Person::display();
cout<<grades<<" "<<id<<endl;
}
main.cpp
#include "Pesron.hpp"
#include "Student.hpp"
#include "graduteStudent.hpp"
#include <iostream>
int main(int argc, const char * argv[]) {
// insert code here...
Student student("ZAID",21,2211,11);
student.display();
return 0;
}
Output
\364\277\357\376\326\241+\310\364\277\357\376\310 21 2211 11
Person::name looks like it is a std::string *. In Person::Person(string Name, int Age) you pass the paramater Name by value and then store the address of this local variable in name. When Name goes out of scope you have a dangling pointer.
(This also applies to void Person::setName(string Name))
Dereferencing Person::name is undefined behaviour, because the object it is pointing doesn't exist anymore. The solution is to simply store a std::string and not just a pointer to it.
So you get something like
class Person {
private:
std::string name;
int age;
public:
Person(std::string Name, int Age) : name(Name), age(Age) {}
};
Related
I need to get in a vector the names of some cities as soon as they are created... In order to accomplish that I created a static vector for the class City, however when I try to compile my code I get the error
error: lvalue required as unary '&' operand
this->cities.push_back(&this);
^~~~
What am I doing wrong?
My code is the following...
#include <iostream>
#include <ctime>
#include <vector>
using namespace std;
class City
{
private:
string name;
static vector<City *> cities;
public:
string getName() { return name; }
City(string name) : name{name}
{
this->cities.push_back(&this);
};
~City(){};
} hongKong{"Hong Kong"}, bangkok{"Bangkok"}, macau{"Macau"}, singapura{"Singapura"}, londres{"Londres"}, paris{"Paris"}, dubai{"Dubai"}, delhi{"Delhi"}, istambul{"Istambul"}, kuala{"Kuala"}, lumpur{"Lumpur"}, novaIorque{"Nova Iorque"}, antalya{"Antalya"}, mumbai{"Mumbai"}, shenzen{"Shenzen"}, phuket{"Phuket"};
int main()
{
}
this is already a City* pointer, so drop the & from &this.
Also, don't forget to actually define the static vector object.
Also, you should account for the class' copy/move constructors and destructor, to make sure you don't miss adding pointers, or leave behind dangling pointers.
Try this:
#include <iostream>
#include <ctime>
#include <vector>
using namespace std;
class City
{
private:
string name;
static vector<City *> cities;
public:
string getName() { return name; }
City(string name) : name{name}
{
cities.push_back(this);
}
City(const City &src) : name{src.name}
{
cities.push_back(this);
}
City(City &&src) : name{std::move(src.name)}
{
cities.push_back(this);
}
~City()
{
cities.erase(std::find(cities.begin(), cities.end(), this));
}
};
vector<City *> City::cities;
City hongKong{"Hong Kong"}, bangkok{"Bangkok"}, macau{"Macau"}, singapura{"Singapura"}, londres{"Londres"}, paris{"Paris"}, dubai{"Dubai"}, delhi{"Delhi"}, istambul{"Istambul"}, kuala{"Kuala"}, lumpur{"Lumpur"}, novaIorque{"Nova Iorque"}, antalya{"Antalya"}, mumbai{"Mumbai"}, shenzen{"Shenzen"}, phuket{"Phuket"};
int main()
{
}
I am new to this. Basically I just learnt how to use class in C++. When I try to print out, the values just seem to be 0. Can anyone help me out? Its supposed to print out:
Susan Myers 47899 Accounting Vice President
Mark Jones 39119 IT Position
Joy Rogers 81774 Manufacturing Engineer
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Employee
{
private:
string name;
int idNumber;
string department;
string position;
public:
Employee()
{
name=" ";
idNumber=0;
department=" ";
position=" ";
}
Employee(string, int, string, string)
{
int id;
string n,d,p;
name=n;
idNumber=id;
department=d;
position=p;
}
Employee(string, int)
{
string n;
int id;
name=n;
idNumber=id;
}
void setName(string)
{
string n;
name=n;
}
void setId(int)
{
int id;
idNumber=id;
}
void setDepartment(string)
{
string d;
department=d;
}
void setPosition(string)
{
string p;
position=p;
}
string getName() const
{
return name;
}
int getId() const
{
return idNumber;
}
string getDepartment() const
{
return department;
}
string getPosition() const
{
return position;
}
};
int main()
{
Employee e1;
Employee e2;
Employee e3;
e1.setName("Susan Meyers");
e2.setName("Mark Jones");
e3.setName("Joy Rogers");
e1.setId(47899);
e2.setId(39119);
e3.setId(81744);
e1.setDepartment("Accounting");
e2.setDepartment("IT");
e3.setDepartment("Manufacturing");
e1.setPosition("Vice President");
e2.setPosition("Programmer");
e3.setPosition("Engineer");
cout<<"---------------------------------------"<<endl;
cout<<"Name"<<setw(6)<<"ID Number"<<setw(10)<<"Department"<<setw(12)<<"Position"<<endl;
cout<<e1.getName()<<setw(6)<<e1.getId()<<setw(10)<<e1.getDepartment()<<setw(12)<<e1.getDepartment()<<endl;
cout<<e2.getName()<<setw(6)<<e2.getId()<<setw(10)<<e2.getDepartment()<<setw(12)<<e2.getDepartment()<<endl;
cout<<e3.getName()<<setw(6)<<e3.getId()<<setw(10)<<e3.getDepartment()<<setw(12)<<e3.getDepartment()<<endl;
return 0;
}
This is what you get when you rely on guesswork rather than properly reading an introductory textbook on C++
A constructor of the Employee class which (apart from a blank line that I've removed) you define as
Employee(string, int, string, string)
{
int id;
string n,d,p;
name=n;
idNumber=id;
department=d;
position=p;
}
has the following effects.
The four arguments passed by the caller are ignored, since they are not named.
Four default-initialised variables (id, n, d, and p) are defined local to the constructor body. id will be uninitialised. The others, since they are std::string, are default-initialised (to an empty string)
The next four statements copy those variables into class members. The result is that initialising idNumber has undefined behaviour (since id is uninitialised) and the three strings are initialised to empty strings.
To get the effect that (I assume) you intend, change this to;
Employee(std::string n, int id, std::string d, std::string p)
{
name=n;
idNumber=id;
department=d;
position=p;
}
Note that I'm calling string by its full name std::string. That allows removing the using namespace std which (among other things) is BAD practice in header files.
Even better, change this to
Employee(const std::string &n, int id, const std::string &d, const std::string &p) :
name(n), idNumber(id), department(d), position(p)
{
}
which passes the strings by const reference (avoids additional copies of std::strings) and uses an initialiser list instead of assigning to members in the constructor.
Similar comments apply to ALL of the member functions of Employee, except that only constructors can have initialiser lists.
Errors made
Presentation
Your code is extremely cluttered, and has much irrelevant stuff.
Syntax
void setPosition(string){
Here your function has no argument! What is string?
Code
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Employee{
public:
string name;
int idNumber;
string department;
string position;
void setName(string n){
name=n;
}
void setId(int k){
int id;
idNumber=id;
}
void setDepartment(string d){
department=d;
}
void setPosition(string p){
position=p;
}
string getName(){
return name;
}
int getId(){
return idNumber;
}
string getDepartment(){
return department;
}
string getPosition(){
return position;
}
};
int main(){
Employee e1;
Employee e2;
Employee e3;
e1.setName("Susan Meyers");
e2.setName("Mark Jones");
e3.setName("Joy Rogers");
e1.setId(47899);
e2.setId(39119);
e3.setId(81744);
e1.setDepartment("Accounting");
e2.setDepartment("IT");
e3.setDepartment("Manufacturing");
e1.setPosition("Vice President");
e2.setPosition("Programmer");
e3.setPosition("Engineer");
cout<<"---------------------------------------"<<endl;
cout<<"Name"<<" "<<"ID Number"<<" "<<"Department"<<" "<<"Position"<<endl;
cout<<e1.getName()<<" "<<e1.getId()<<" "<<e1.getDepartment()<<" "<<e1.getPosition()<<endl;
cout<<e2.getName()<<" "<<e2.getId()<<" "<<e2.getDepartment()<<" "<<e2.getPosition()<<endl;
cout<<e3.getName()<<" "<<e3.getId()<<" "<<e3.getDepartment()<<" "<<e3.getPosition()<<endl;
}
Output
---------------------------------------
Name ID Number Department Position
Susan Meyers 32767 Accounting Vice President
Mark Jones 32767 IT Programmer
Joy Rogers 32767 Manufacturing Engineer
Explanation
I have shortened your code by 50%(shows how much redundant stuff you had), and here is a working code.
void setDepartment(string d){
department=d;
}
Here, string d is defined IN the function as an argument. Note that your code also cout<< department twice, and I have corrected that for you in my above code.
Hope this helps.
This question already has answers here:
Why does C++ allow us to surround the variable name in parentheses when declaring a variable?
(2 answers)
Closed 5 years ago.
Hello,
I'm trying to instantiate an anonymous object with a std::string variable 'name'. But intellisenen gives me error saying
E0291 no default constructor exists for class "Player" GoldGame e:\C++ Projects\Hello World\GoldGame\GoldGame.cpp 17
I have provided a constructor which can just take a std::string variable since other parameters are provided with default value.
Can you guys shed some light on this?
What confuses me even more is that when I change
Player(name);
to
Player a(name);
or to
Player("test");
then intellisense becomes totally fine with those.
GoldGame.cpp
#include "stdafx.h"
#include "Creature.h"
#include "Player.h"
#include <iostream>
#include <string>
int main()
{
std::cout << "Enter your name: ";
std::string name;
std::cin >> name;
Player(name);
return 0;
}
Creature.h
#pragma once
#include <string>
class Creature
{
public:
Creature(const std::string &name, const char symbol, const int health, const int damage, const int gold);
~Creature();
//getters
const std::string& getName() { return m_name; }
const char getSymbol() { return m_symbol; }
const int getHealth() { return m_health; }
const int getDamage() { return m_damage; }
const int getGold() { return m_gold; }
//health, gold and dead
void reduceHealth(const int healthMinus);
void addGold(const int gold);
bool isDead();
private:
std::string m_name;
char m_symbol;
int m_health;
int m_damage;
int m_gold;
};
Creature.cpp
#include "stdafx.h"
#include "Creature.h"
Creature::Creature(const std::string & name, const char symbol, const int health, const int damage, const int gold)
:m_name(name), m_symbol(symbol), m_health(health), m_damage(damage), m_gold(gold)
{
}
Creature::~Creature()
{
}
void Creature::reduceHealth(const int healthMinus)
{
m_health -= healthMinus;
}
void Creature::addGold(const int gold)
{
m_gold += gold;
}
bool Creature::isDead()
{
if (m_health>0)
{
return true;
}
else
{
return false;
}
}
Player.h
#pragma once
#include "Creature.h"
#include <string>
class Player :
public Creature
{
public:
Player(const std::string &name, const char symbol='#', const int health=10, const int damage=1, const int gold=0);
~Player();
const int getLevel() { return m_level; }
void levelUp();
bool hasWon();
private:
int m_level;
};
Player.cpp
#include "stdafx.h"
#include "Player.h"
Player::Player(const std::string & name, const char symbol, const int health, const int damage, const int gold)
:Creature(name,symbol,health,damage,gold)
{
}
Player::~Player()
{
}
void Player::levelUp()
{
++m_level;
}
bool Player::hasWon()
{
if (m_level>=20)
{
return true;
}
else
{
return false;
}
}
Player(name); does not do what you think it does. It declares a new variable name of type Player and calls a default constructor. If you want to instantiate an anonymous Player variable then you need to write
(Player(name));
// or
Player{name}; // list initialization since C++11
This program compilation succeeded but it doesn't work.
I guess it has something to do with the assignment operator or the copy constructor but I can't figure out what...
Header:
class employee{
char *name;
unsigned int salary;
public:
employee();
employee(const char*);
employee(const char*,unsigned int);
employee (const employee&);
employee operator = (employee);
void init(const char*,unsigned int);
void print();
~employee();
};
Cpp:
#include <iostream>
#include <string>
#include "class.h"
using namespace std;
employee::employee() : salary(1000)
{
name=new char[20];
}
employee::employee(const char* ename) : salary(1000)
{
strcpy_s(name,20,ename);
}
employee::employee(const char* ename,unsigned int salary)
{
name=new char[20];
strcpy_s(name,20,ename);
this->salary=salary;
}
employee::employee(const employee& emp)
{
name=new char[20];
int i=0;
while (name[i]!='\0')
{
name[i]=emp.name[i];
i++;
}
salary=emp.salary;
}
void employee::init(const char* ename, unsigned int salary)
{
name=new char[20];
strcpy_s(name,20,ename);
this->salary=salary;
}
void employee::print()
{
cout<<"name: ";
int i=0;
while (name[i]!='\0')
{
cout<<name[i];
i++;
}
cout<<"\n"<<"salary: "<<salary<<endl;
}
employee employee::operator = (employee emp)
{
strcpy_s(name,20,const_cast <const char*>(emp.name));
emp.salary=salary;
return *this;
}
employee::~employee()
{
delete [] name;
}
Main:
#include <iostream>
#include "class.h"
using namespace std;
int main()
{
employee emp1 ("Bill Jones",5000),emp5("Michael Adams");
employee emp2;
emp2=emp1;
employee emp3;
emp3=emp2;
employee * workers= new employee [3];
workers[0]=emp3;
workers[1]= employee("katy Ashton");
delete [] workers;
}
While you may be doing this as an exercise, I recommend you read up on What is the Rule of Three? It and similar FAQs will guide you on how to properly overload copy/assignment operators and writing your own copy constructors and handle dynamic memory appropriately. For now, to avoid error-prone code, I suggest you use std::string and forgo overloading entirely. Your new class should look like this:
#include <iostream>
using namespace std;
class employee{
std::string name;
unsigned int salary;
public:
employee();
employee(std::string);
employee(std::string,unsigned int);
void init(std::string,unsigned int);
void print();
~employee();
};
employee::employee() : salary(1000)
{
name = "";
}
employee::employee(std::string ename) : salary(1000)
{
name = ename;
}
employee::employee(std::string ename,unsigned int salary)
{
name = ename;
this->salary=salary;
}
void employee::print()
{
cout<<"name: "<<name;
cout<<"\n"<<"salary: "<<salary<<endl;
}
employee::~employee()
{
}
int main()
{
employee emp1 ("Bill Jones",5000),emp5("Michael Adams");
employee emp2;
emp2=emp1;
employee emp3;
emp3=emp2;
employee * workers= new employee [3];
workers[0]=emp3;
workers[1]= employee("katy Ashton");
for (int i = 0; i < 2; i++)
{
workers[i].print();
}
delete [] workers;
}
I think you are missing name = new char[20]; in the employee constructor that takes just the name parameter
I don't know what the error message is, but I guess the reason is:
employee::employee(const char* ename) : salary(1000)
{
strcpy_s(name,20,ename);
}
you don't allocate any space for name here and you use this constructor later: ,emp5("Michael Adams");
Therefore it crashes (I guess)
I believe that this part is wrong:
while (name[i]!='\0')
{
name[i]=emp.name[i];
i++;
}
the while-condition should be emp.name[i]!='\0'.
(consider using strcpy_s, which does the same thing.)
Another problem is in your employee::employee(const char* ename) constructor, where you copy into array, which is not allocated. You need to allocate it first:
employee::employee(const char* ename) : salary(1000)
{
name = new char[20]; // typo! it was 10... better use defines in this situation!
strcpy_s(name,20,ename);
}
Of course, you should describe your problem more precisely.
I'm writing a program for a homework assignment. The program compiles and runs, but has a bad access error.
This is main.cpp
#include <iostream>
#include <string>
#include "Mammal.h"
#include "Dog.h"
#include "Horse.h"
#include "Pig.h"
#include "Cat.h"
using namespace std;
//Seed for ease of grading
const int SEED=100;
const int NUM_ANIMALS=5;
const int WEIGHT_LIMIT=150;
void MammalAssignment(const Mammal * new_Mammal, int choice, string newName);
void UserChoice(const Mammal * new_Mammal);
void ListAnimal(const Mammal *new_Mammal);
int main()
{
string newName, newWeight;
srand(SEED);
Mammal *new_Mammal[NUM_ANIMALS];
UserChoice(*new_Mammal);
for(int i=0; i<NUM_ANIMALS; i++)
ListAnimal(new_Mammal[i]);
//Program pauses for user input to continue
char exit_char;
cout<<"\nPress any key and <enter> to exit\n";
cin>>exit_char;
return 0;
}
void UserChoice(const Mammal * new_Mammal)
{
int choice;
bool choiceGood;
string newName;
for(int i=0;i<NUM_ANIMALS; i++){
choiceGood=false;
while(choiceGood==false)
{
cout<<"-Please choose a number 1-4 for the corresponding animal-\n"
<<"1-Dog\n2-Horse\n3-Pig\n4-Cat\n";
cin>>choice; //User choice
if(choice<=0 || choice >=5){
cout<<"Your choice is invalid\n\n";
continue;
}
choiceGood=true;
} //While loop
cout<<"\nPlease enter a name for the animal you have chosen(Ex. Fido).\n";
cin>>newName;
MammalAssignment(&new_Mammal[i], choice, newName);
} //For loop
}
void MammalAssignment(const Mammal * new_Mammal, int choice, string newName)
{
if(choice==1){
Dog newDog(rand()%(WEIGHT_LIMIT+1), newName);
new_Mammal=&newDog;
}
else if(choice==2){
Horse newHorse(rand()%(WEIGHT_LIMIT+1), newName);
new_Mammal=&newHorse;
}
else if(choice==3){
Pig newPig(rand()%(WEIGHT_LIMIT+1), newName);
new_Mammal=&newPig;
}
else if(choice==4){
Cat newCat(rand()%(WEIGHT_LIMIT+1), newName);
new_Mammal=&newCat;
}
}
void ListAnimal(const Mammal *new_Mammal)
{
cout<<"-------------------------\nName:"
<<new_Mammal->GetName()<<"\nWeight: "
<<new_Mammal->GetWeight();
}
Mammal.h
#ifndef MAMMAL_H
#define MAMMAL_H
using namespace std;
class Mammal
{
public:
Mammal(); //Default constructor
Mammal( int newWeight); //Parameterized constructor
void SetWeight(int newWeight);
virtual string GetName() const;
int GetWeight() const;
//virtual function to be defined by derived animal classes
virtual void Speak() const;
private:
int weight;
};
#endif
Mammal.cpp
#include <iostream>
#include <string>
#include "Mammal.h"
using namespace std;
Mammal::Mammal()
{
SetWeight(0);
cout<<"\nInvoking default Mammal Constructor\n";
}
Mammal::Mammal( int newWeight)
{
SetWeight(newWeight);
cout<<"\nInvoking parameterized Mammal Constructor\n";
}
void Mammal::SetWeight(int newWeight)
{
weight=newWeight;
}
int Mammal::GetWeight() const
{
return weight;
}
string Mammal::GetName() const
{}
void Mammal::Speak() const
{
cout<<"\nLadies and gentlemen, the mammal speaks...\n";
}
Dog.h
#ifndef DOG_H
#define DOG_H
#include "Mammal.h"
using namespace std;
class Dog: public Mammal
{
public:
Dog(); //Default constructor
Dog(const int& newWeight,const string& newName); //Parameterized constructor
void SetName(string newName);
string GetName() const;
//mammal virtual function
virtual void Speak() const;
private:
string name;
};
#endif
Dog.cpp
#include <iostream>
#include <string>
#include "Dog.h"
using namespace std;
//Default constructor
Dog::Dog()
{
cout<<"\nInvoking default Dog constructor\n";
}
//Parameterized constructor
Dog::Dog( const int& newWeight,const string& newName):Mammal(newWeight)
{
SetName(newName);
cout<<"\nInvoking parameterized Dog constructor.\n";
}
void Dog::SetName(string newName)
{
name=newName;
}
string Dog::GetName() const
{
return name;
}
//mammal virtual function
void Dog::Speak() const
{
Mammal::Speak();
cout<<"\nWoof!\n";
}
The other derived classes(horse, pig, and cat) are all identical to Dog. I'm getting a Exc_Bad_Access error when ListAnimals() gets to GetWeight(). As far as I can tell it's returning the right file type. Any help would be awesome
Your MammalAssignment function is returning a pointer to a local variable. Once the function returns, that memory (which was on the stack) is gone and you will crash when you access it as an object of the relevant mammal type.
You need to return a pointer to memory allocated using operator new, or possibly just an object instead of a pointer, assuming suitable copy semantics are implemented in your Mammal classes.
A revision (or initial self-education?)of memory management in C++ would be in order before you go any further. See also smart pointers, to avoid new/delete where possible and make your life easier.
Mammal *new_Mammal[NUM_ANIMALS];
You need to allocate memory using new !
Mammal *new_Mammal = new Mammal[NUM_ANIMALS];
Also I think your UserChoice function should take the pointer as a reference and not as a const value to be able to change the actual content.