Hello I didn't use C++ for years now, so I'm kinda rusty and can't figure this out!
I have this code | person.h
#ifndef PERSON_H
#define PERSON_H
#include<string>
class Person {
private:
std::string fName, lName;
int age;
enum professionEnum {
Barber,
Developer,
Marketer
} profession;
public:
Person();
Person(std::string fName, std::string lName, int profession);
void setFName(std::string fName);
void print();
};
#endif
a simple person class.
What I want to do is for my constructor Person() to take an int, example :
Person me = Person("me", "meow", 0); // This should assign "me" to Barber, enum index is 0.
Here is what I tried so far (all errors):
this->profession = professionEnum::profession;
this->profession = 0;
this->profession = professionEnum(profession);
Here is the full person.cpp code
#include "person.h"
#include <iostream>
Person::Person() {
this->age = 18;
this->fName = "Default";
this->lName = "Default";
}
Person::Person(std::string fName, std::string lName, int profession) {
this->fName = fName;
this->lName = lName;
this->profession = professionEnum::profession;
this->profession = 0;
this->profession = professionEnum(profession);
}
void Person::print() {
std::cout << "Age : " << this->age << ", FName : " << this->fName << ", LName : " << this->lName << std::endl;
}
Thanks for your help
PS: If you spot any bad practices / bad code, please tell me.
Related
i just opened up c++ today for the first time almost, and i tried doing some inheritance.
I have a class called Person and three classes that derive from Person called:
Retiree,
Adult,
Child.
The console asks for your age and in the case that you type 30 into the console i want to make a new adult object, and here i want to pass in the parameters: age, name and discount.
In java i would just call the constructor in the child class, as it has the super(a, b, c) in it. But when i try to do it here, it won't work, and i can't seem to figure out why.
Down below is two cpp files for Person and Adult showing their constructors and lastly the Main.cpp
I get this error when i try to create the object "Unhandled exception at 0x759EA842 in LearnCPP.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x00AFF514."
Person.h
#pragma once
#include <String>
#include "BudgetAccount.h"
class Person
{
private:
public:
Person(int32_t age, std::string name);
int32_t getAge();
void setAge(int32_t age);
std::string getName();
void setName(std::string name);
protected:
int32_t age;
std::string name;
};
Person.cpp
#include "Person.h"
#include <String>
Person::Person(int32_t age, std::string name)
{
this->age = age;
this->name = name;
}
int32_t Person::getAge()
{
return age;
}
void Person::setAge(int32_t age)
{
this->age = age;
}
std::string Person::getName()
{
return name;
}
void Person::setName(std::string name)
{
this->name = name;
}
Adult.h
#pragma once
#include "Person.h"
class Adult : public Person
{
private:
double discount;
public:
Adult(double discount);
};
Adult.cpp
#include "Adult.h"
Adult::Adult(double discount) : Person(age, name)
{
this->discount = discount;
}
Main.cpp
#include <iostream>
#include "Person.h"
#include "Adult.h"
int main()
{
std::cout << "Hello Customer" << std::endl;
std::cout << "Down below you see a list of cities" << std::endl;
std::cout << "Please enter your name" << std::endl;
//Cin
std::string name;
std::cin >> name;
std::cout << "Please enter your age" << std::endl;
std::int32_t age;
std::cin >> age;
//Check if the entered age is child, adult or retiree
Adult user(50.0);
std::cout << "Please select which city you want to travel to" << std::endl;
return 0;
}
I think this is your problem:
Adult::Adult(double discount) : Person(age, name)
{
this->discount = discount;
}
You haven't passed in an age or name to this constructor, so it's using them from the parent class -- whose constructor hasn't been called yet.
As previously mentioned, you haven't passed the value for name and age.
One solution to this is that you can change the constructor to take in the values for age and name.
Another solution is that you can define default constructor. You can also set default values in the parameterised constructor.
Person::Person(int32_t age = 0, std::string name = ""){
this->age = age;
this->name = name; }
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'mm getting a bit confused why this isn't printing the name!
I've got a human.cpp :
#include <string>
#include <iostream>
#include "human.h"
human::human(int age, human *n){
m_age=age;
name = new char[2];
human::~human() = default;
void human::printDetails(){
std::cout <<"name is " << name << " age is " << m_age << std::endl;
}
and human.h:
class human {
public: //: needed
human(int age, human *name);
~human();
void printDetails();
private :
char *name;
int m_age;
};
and finally the main.cpp:
#include <iostream>
#include <string>
#include "human.h"
int main()
{
human *Alex = new human(10, Alex); //pointer // needs argument //should have both age and name
Alex->printDetails(); //print not Print
}
So my issue is: it prints the age, but does not print the name? Any suggestions? Thanks :)
There is no need for any new in your code. Since you #included <string> in your code I assume you want to use it:
#include <string>
#include <iostream>
class Person
{
int age;
std::string name;
public:
Person(int age, std::string name)
: age { age },
name { name }
{}
int get_age() const { return age; }
std::string const& get_name() const { return name; }
void print_details() const {
std::cout << "My name is " << name << ". I am " << age << " years old.\n";
}
};
int main()
{
Person p{ 19, "Alex" };
p.print_details();
}
If you *really* want to do it the hard waytm:
#include <cstring> // std::strlen()
#include <utility> // std::exchange(), std::swap()
#include <iostream>
class Person
{
char *name_;
int age_;
public:
Person(int age, char const *name) // constructor
// we don't want to call std::strlen() on a nullptr
// instead allocate just one char and set it '\0'.
: name_ { new char[name ? std::strlen(name) + 1 : 1]{} },
age_ { age }
{
if (name)
std::strcpy(name_, name);
}
Person(Person const &other) // copy-constructor
: name_ { new char[std::strlen(other.name_) + 1] },
age_ { other.age_ }
{
std::strcpy(name_, other.name_);
}
Person(Person &&other) noexcept // move-constructor
: name_ { std::exchange(other.name_, nullptr) }, // since other will be
age_ { other.age_ } // wasted anyway, we
{} // "steal" its resource
Person& operator=(Person other) noexcept // copy-assignment operator
{ // since the parameter other got
std::swap(name_, other.name_); // copied and will be destructed
age_ = other.age_; // at the end of the function we
return *this; // can simply swap the pointers
} // - know as the copy&swap idiom.
~Person() { delete[] name_; } // destructor
void print_details() const
{
std::cout << "I am " << name_ << ". I am " << age_ << " years old.\n";
}
};
int main()
{
Person p{ 19, "Alex" };
p.print_details();
}
If you don't want to implement the special member functions you'd have to = delete; them so the compiler-generated versions - which won't work correctly for classes managing their own resources - won't get called by accident.
#include <iostream>
#include <cstring>
#include <new>
using namespace std;
class human {
public:
human(int age, const char * name)
{
m_age=age;
m_name = new char[strlen(name)+1];
strcpy(m_name,name);
}
~human()
{
delete[] m_name;
}
void printDetails()
{
std::cout <<"name is " << m_name << " age is " << m_age << std::endl;
}
private :
char *m_name;
int m_age;
};
int main()
{
human *Alex = new human(10, "alex"); //pointer // needs argument //should have both age and name
Alex->printDetails(); //print not Print
delete Alex;
return 0;
}
You need to read more. The example you shared was wrong at many level, also read about dynamic memory management.
I guess you're confused with the second parameter of the human constructor. Look at this changes:
human.h
class human {
public:
human(int age, char *name);
human(const human& h);
human& operator=(const human& h);
void printDetails();
virtual ~human();
private:
int age;
char *name;
};
human.cpp
human::human(int _age, char *_name) {
age = _age;
name = new char[strlen(_name)+1];
strcpy(name, _name);
}
human::human(const human& _h) { //Copy constructor
age = _h.age;
name = new char[strlen(_h.name)+1];
strcpy(name, _h.name);
}
human& human::operator=(const human& _h) { //Copy assignment operator
age = _h.age;
name = new char[strlen(_h.name)+1];
strcpy(name, _h.name);
return *this;
}
void human::printDetails(){
std::cout <<"name is " << name << " age is " << age << std::endl;
}
human::~human() { //Destructor
delete[] name;
}
main.cpp
int main() {
human *alex = new human(10, "Alex");
alex->printDetails();
human *anotherAlex = new human(*alex);
anotherAlex->printDetails();
delete alex;
delete anotherAlex;
}
A suggestions: I would use Human as the class names and alex for the variable names. (See how I capitalized them)
For beginner you may use std::string, so you already included it. ))
human.h
#include <string>
class human
{
public: //: needed
human(int age, std::string name);
void printDetails();
private :
std::string name;
int m_age;
};
human.cpp
#include <iostream>
#include "human.h"
human::human(int age, std::string n)
{
m_age = age;
name = n;
}
void human::printDetails()
{
std::cout <<"name is: " << name << " age is: " << m_age << std::endl;
}
main.cpp
#include "human.h"
int main()
{
human *Alex = new human(10, "Alex");
Alex->printDetails();
}
#include <string>
struct Person
{
Person(std::string name) {
}
std::string greet(std::string other_name)
{
name="Joe";
return "Hi " + other_name + ", my name is " + name;
}
std::string name;
};
With the greet function, I want a name (e.g. John) to be returned, however, the function, as it is written, returns nothing. It is blank after the "my name is" string.
How do I properly assign the value of name within the struct, such that I can have a proper return?
Thank you for any nudging in the right direction!
It’s not initializing the name field from the parameter in the constructor. i.e. change the constructor to:
#include <string>
struct Person
{
Person(std::string name) : name(name) {} {
}
std::string greet(std::string other_name)
{
return "Hi " + other_name + ", my name is " + name;
}
std::string name;
};
This should solve your problem and will return the desired solution.
try using breakpoints?
i ran the code using g++ with minGW and got the same result, then changed it to this
#include <iostream>
#include <string>
using std::string;
struct Person
{
string name;
Person(string _name) {
name = _name;
}
string greet(string other_name)
{
return "Hi " + other_name + ", my name is " + name;
}
};
int main()
{
Person person("foo");
std::cout << person.greet("bar");
return 0;
}
the problem is that name is null, but the compiler doesn't give any warnings
this outputs "hello bar, my name is foo" , i compiled myself and got correct result
#include <string>
struct Person
{
Person(std::string _name) {
name = _name;}
std::string greet(std::string other_name)
{
return "Hi " + other_name + ", my name is " + name;
}
std::string name;
};
This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 7 years ago.
I recently started learning object oriented programming..for the following code, I am getting the linker error !!
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class person{
public:
string name;
person();
person(string n){
name = n ;
}
void setName(string k){
name = k;
}
string getName(){
return name;
}
};
class student : public person {
public:
string major;
void setMajor(string m){
major = m;
}
string getMajor(){
return major;
}
};
class faculty : public person{
public:
string department;
faculty(string dept){
department = dept;
}
void setDepartment(string depart){
department = depart;
}
string getDepartment(){
return department;
}
};
int main() {
student s;
s.setName("james");
s.setMajor("computer science");
string p = s.getName();
string p2 = s.getMajor();
cout << "student name and mjor is :" << p << p2 << endl;
faculty f("nanotech");
f.setName("chris");
f.setDepartment("electrical");
string f1 = f.getName();
string f2 = f.getDepartment();
cout << "facult name and department :" << f1 << f2 << endl;
return 0;
}
The following error i am getting , when i try to compile the code.
/tmp/ccYHu2de.o: In function `faculty::faculty(std::string)':
person.cpp:(.text._ZN7facultyC2ESs[_ZN7facultyC5ESs]+0x19): undefined reference to `person::person()'
/tmp/ccYHu2de.o: In function `student::student()':
person.cpp:(.text._ZN7studentC2Ev[_ZN7studentC5Ev]+0x15): undefined reference to `person::person()'
collect2: error: ld returned 1 exit status
In your class person you have a constructor that is declared but is not defined. The compiler let you compile the class but then the linker looks for an implementation (which is called forward declaration):
class person{
public:
string name;
person(); //constructor only declared
person(string n){
name = n ;
}
.....
};
The problem is that you inherit from person in your student and faculty, you use the default constructor but you never implement it. Try to add an implementation and the linker error will disappear:
class person{
public:
string name;
person(){} //constructor implemented
person(string n){
name = n ;
}
.....
};
The Problem is that you need to implement the constructor of the person class, Try this code: http://ideone.com/NfXP7R
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class person{
public:
string name;
person() {
}
person(string n){
name = n ;
}
void setName(string k){
name = k;
}
string getName(){
return name;
}
};
class student : public person {
public:
string major;
void setMajor(string m){
major = m;
}
string getMajor(){
return major;
}
};
class faculty : public person{
public:
string department;
faculty(string dept){
department = dept;
}
void setDepartment(string depart){
department = depart;
}
string getDepartment(){
return department;
}
};
int main() {
student s;
s.setName("james");
s.setMajor("computer science");
string p = s.getName();
string p2 = s.getMajor();
cout << "student name and mjor is :" << p << p2 << endl;
faculty f("nanotech");
f.setName("chris");
f.setDepartment("electrical");
string f1 = f.getName();
string f2 = f.getDepartment();
cout << "facult name and department :" << f1 << f2 << endl;
return 0;
}
Hello and thanks in advance for helping,
I've the problem that I don't see any output on my eclipse console (on linux ubuntu 12.04).
I have this little C++ program:
Addressverwaltung.cpp:
#include <iostream>
#include "Adresse.h"
using namespace std;
int main() {
cout << "asdf";
Adresse lAdresse1("Max", "Tester", "Strasse 21", 6423, "lol", "asdf#hotmail.com");
lAdresse1.printAdresse();
lAdresse1.setName("Testing");
lAdresse1.printAdresse();
return 0;
}
Adresse.h:
#ifndef Adresse_h
#define Adresse_h
#include <iostream>
#include <string>
class Adresse{
public:
Adresse(std::string pVorname, std::string pName);
Adresse(std::string pVorname, std::string pName, std::string pStrasse, int pPlz, std::string pOrt, std::string pEmail);
void printAdresse();
void setVorname(std::string pVorname);
void setName(std::string pName);
std::string getName();
private:
std::string mVorname;
std::string mName;
std::string mStrasse;
int mPlz;
std::string mOrt;
std::string mEmail;
};
#endif
Adresse.cpp:
#include "Adresse.h"
Adresse::Adresse(std::string pVorname, std::string pName){
mVorname = pVorname;
mName = pName;
}
Adresse::Adresse(std::string pVorname, std::string pName, std::string pStrasse, int pPlz, std::string pOrt, std::string pEmail){
mVorname = pVorname;
mName = pName;
mStrasse = pStrasse;
mPlz = pPlz;
mOrt = pOrt;
mEmail = pEmail;
}
void Adresse::printAdresse(){
std::cout << "ADRESSE:";
std::cout << mVorname + mName;
std::cout << "STRASSE: " + mStrasse;
std::cout << "PLZ: " + mPlz;
std::cout << "EMAIL: " + mEmail;
}
void Adresse::setVorname(std::string pVorname){
mVorname = pVorname;
}
void Adresse::setName(std::string pName){
mName = pName;
}
std::string Adresse::getName(){
return mName;
}
Whenever I click "run" I see the message "make all
make: Nothing to be done for `all'." for about 4 seconds, afterwards the console is empty. I tried cleaning and rebuilding the project but that doesn't help.
Does anyone know how to fix this?
Put a cout.flush() before the return in main() function. That should help:
int main() {
cout << "asdf";
Adresse lAdresse1("Max", "Tester", "Strasse 21", 6423, "lol", "asdf#hotmail.com");
lAdresse1.printAdresse();
lAdresse1.setName("Testing");
lAdresse1.printAdresse();
cout.flush(); // <<<<<<<<<<<<<<<<<<<<<<<<
return 0;
}