C++ Array containing base/derived class objects [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I'm trying to put together an assignment here and got stuck on one point. The question is to create Person class with Student derived class. Then overload both << and >> operators. In the end create checking program to create array of 20 Persons and keep loading either Person or Student. At any point we can print what we have by far - Person output is Name char*/Age int/Parents *char[2], Student output is Name char*/Age int/ID int.
My problem is with the array point - I can't figure out how to implement this and right now I'm stuck with:
Array of pointers to person
We choose if its person/student
istream to get the data
Here is main code part:
#include <iostream>
#include <conio.h>
#include "Header.h"
using namespace std;
int main()
{
char choice;
Person* Tablica[20];
Person* temp;
int i = 0;
while (1)
{
cout << "choices:" << endl;
cout << "(p)erson, (s)tudent, s(h)ow, (e)nd" << endl;
choice = _getch();
if (choice == 'h' || choice == 'H'){
for (int n = 0; n < i; n++){
cout << *Tablica[n] << endl;
}
}
if (choice == 'e' || choice == 'E'){ break; }
if (choice == 'p' || choice == 'P'){
temp = new Person;
cin >> *temp;
Tablica[i] = temp;
cout << *Tablica[i] << endl;
i++;
}
if (choice == 'S' || choice == 's'){
temp = new Student;
cin >> *temp;
Tablica[i] = temp;
cout << *Tablica[i] << endl;
i++;
}
}
system("PAUSE");
return 0;
}
I'm able to load first person/student and then code breaks without error.
So what I'm asking here is, could you look at the code and perhaps point me in the right direction?
Disclaimer: We have to use array, no vectors etc. Yes, conio.h is there as well and it has to stay... Obviously I'm beginner.
Person:
#include <iostream>
class Person
{
public:
Person();
Person(const Person&);
Person(char* n, int a, char* Parent1, char* Parent2);
char* getName();
int getAge();
char* getDad();
char* getMum();
virtual ~Person();
virtual Person operator=(const Person &);
virtual Person operator+(const Person &);
virtual Person operator+=(Person &);
virtual void write(std::ostream&);
virtual void read(std::istream&);
friend std::istream& operator>>(std::istream&, Person &);
friend std::ostream& operator<<(std::ostream&, Person &);
protected:
char* name;
int age;
char* ParentName[2];
};
class Student : public Person
{
public:
Student();
Student(const Student&);
Student(char* name, int age, int id);
virtual ~Student();
int ident();
Student operator=(const Student &);
Student operator+(const Student &);
Student operator+=(Student &);
virtual void write(std::ostream&);
virtual void read(std::istream&);
friend std::istream& operator>>(std::istream&, Student &);
friend std::ostream& operator<<(std::ostream&, Student &);
private:
int ID;
};
Class
#include "Header.h"
Person::Person(){
name = 0;
age = 0;
ParentName[0] = 0;
ParentName[1] = 0;
}
Person::Person(const Person & other)
{
name = other.name;
age = other.age;
ParentName[0] = other.ParentName[0];
ParentName[1] = other.ParentName[1];
}
Person::Person(char* n, int a, char* Parent1, char* Parent2){
name = n;
age = a;
ParentName[0] = Parent1;
ParentName[1] = Parent2;
}
Person::~Person(){}
char* Person::getName(){ return name; }
int Person::getAge(){ return age; }
char* Person::getDad(){ return ParentName[0]; }
char* Person::getMum(){ return ParentName[1]; }
Person Person::operator=(const Person & other){
name = other.name;
age = other.age;
ParentName[0] = other.ParentName[0];
ParentName[1] = other.ParentName[1];
return *this;
}
Person Person::operator+=(Person & other){
int i;
i = strlen(name) + strlen(other.name) + 4;
char * temp = new char[i];
strcpy_s(temp, i, name);
strcat_s(temp, i, " - ");
strcat_s(temp, i, other.name);
name = temp;
Person wynik(name, age, ParentName[0], ParentName[1]);
return wynik;
}
Person Person::operator+(const Person & other){
int i;
i = strlen(name) + strlen(other.name) + 4;
char * temp = new char[i];
strcpy_s(temp, i, name);
strcat_s(temp, i, " - ");
strcat_s(temp, i, other.name);
Person wynik(temp, age, ParentName[0], ParentName[1]);
return *this;
}
void Person::write(std::ostream& os)
{
os << "Osoba: name = " << this->getName() << ", wiek = " << this->getAge() << ", rodzice: " << this->getDad() << ", " << this->getMum();
}
std::ostream& operator<<(std::ostream& os, Person & other){
other.write(os);
return os;
}
void Person::read(std::istream& is)
{
char* name;
name = new char;
std::cout << "name: " << std::endl;
is >> name;
std::cout << "age: " << std::endl;
int age;
is >> age;
std::cout << "dad: " << std::endl;
char* dad;
dad = new char;
is >> dad;
std::cout << "mum: " << std::endl;
char* mum;
mum = new char;
is >> mum;
Person p(name, age, dad, mum);
*this = p;
}
std::istream & operator>>(std::istream & is, Person & os){
os.read(is);
return is;
}
Student::Student() : Person(){}
Student::Student(const Student& student) : Person(student){
ID = student.ID;
}
Student::Student(char* name, int age, int id) : Person(name, age, 0, 0){
ID = id;
}
Student::~Student(){}
Student Student::operator=(const Student & student){
Person::operator=(static_cast<Person const&>(student));
ID = student.ID;
return *this;
}
Student Student::operator+=(Student & student){
Student wynik(*this);
wynik.Person::operator=(wynik.Person::operator+=(student));
return wynik;
}
Student Student::operator+(const Student& student)
{
Person::operator+(static_cast<Person const&>(student));
return *this;
}
void Student::write(std::ostream& os)
{
os << "Student: name = " << this->getName() << ", age = " << this->getAge() << ", legitymacja: " << this->ident() << std::endl;
}
int Student::ident(){ return ID; }
std::ostream& operator<<(std::ostream& os, Student & other){
other.write(os);
return os;
}
void Student::read(std::istream& is)
{
char* name;
name = new char[20];
std::cout << "name: " << std::endl;
is >> name;
std::cout << "age: " << std::endl;
int age;
is >> age;
std::cout << "ID: " << std::endl;
int id;
is >> id;
Student s(name, age, id);
*this = s;
}
std::istream & operator>>(std::istream & is, Student & st){
st.read(is);
return is;
}

Does this compile?
Table[i] = *temp;
Table is an array of pointers to Person
temp is a pointer to Person
You are trying to put an object into an array that holds pointers. Dereferencing *temp gives you an object - you need a pointer to an object, so don't dereference it there. I would expect the compiler to complain about that... does it?
Also, check your second if statement - it says (choice == 'S' || choice == 'p'), which is probably not what you meant. Both if blocks will execute if choice == 'p'...
And in Person::read() you've only allocated a single character for name. That is likely to end badly...

Related

LMS error no operator = matches these operands

So for practice purposes I am creating a library management system using composition, to understand and practice the concept of composition.so i have a book class and a user class. i am composing a pointer of book class in the user class. i am using dma (dynamic memory allocation) for the add function.but i am getting this error that i am unable to debug.
Error (active) E0349 no operator "=" matches these operands PRAcTice
here's the whole code for understanding
#ifndef LMS_H
#define LMS_H
#include <iostream>
#include <string>
using namespace std;
class book {
private:
string bname;
int ISBN;
string author;
string publisher;
public:
book(string n = " ", int i = 0, string a = " ", string p = " ") {
bname = n;
ISBN = i;
author = a;
publisher = p;
}
void setbname(string a) {
bname = a;
}
string getbname() {
return bname;
}
void setisbn(int b) {
ISBN = b;
}
int getisbn() {
return ISBN;
}
void setauthor(string c) {
author = c;
}
string getauthor() {
return author;
}
void setpublisher(string d) {
publisher = d;
}
string getpublisher() {
return publisher;
}
friend ostream & operator << (ostream & COUT, book & rhs);
};
ostream & operator << (ostream & COUT, book & rhs) {
COUT << "Book Name: " << rhs.getbname() << endl;
COUT << "ISBN: " << rhs.getisbn() << endl;
COUT << "Author: " << rhs.getauthor() << endl;
COUT << "Publisher: " << rhs.getpublisher() << endl;
}
class user {
private:
string name;
int id;
string password;
book * b;
int bno;
public:
user(string m = " ", int q = 0, string n = " ", book * bx = NULL, int no = 0) {
name = m;
id = q;
password = n;
b = bx;
}
void setname(string a) {
name = a;
}
string getbname() {
return name;
}
void setid(int b) {
id = b;
}
int getid() {
return id;
}
void setpassword(string c) {
password = c;
}
string getpassword() {
return password;
}
void setbno(int d) {
bno = d;
}
int getisbn() {
return bno;
}
void setbook(book a[]) {
b = new book[bno];
for (int i = 0; i < bno; i++) {
b[i].setbname(a[i].getbname());
b[i].setisbn(a[i].getisbn());
b[i].setauthor(a[i].getauthor());
b[i].setpublisher(a[i].getpublisher());
}
}
book * getbook() {
return b;
}
book * add(book b) {
b = new book[bno + 1];
}
};
#endif // !"LMS_H"
The problem is that the object b on the left hand side of the assignment b = new book[bno + 1]; is of type book while the object on the right hand side is of type book*.
//---v----------------------->type of object b is book
b = new book[bno + 1];
//-------^^^^^^^^^^^^^^^^----type of the resulting object on rhs is book*
That is there is a mismatch in the type on the left hand side and right hand side of the assignment and since there is no overloaded operator= that has parameter of type book and book* you get the mentioned error.
Additionally you're missing return statements inside operator<< and inside add.

I get this error"Exception thrown at 0x7BE7B103 (msvcp140d.dll) : when running my code [closed]

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 2 years ago.
Improve this question
my code has 3 classes user, book and userList the user list is a class that creates an array of users. I am a beginner so any help would be greatly appreciated.
I will list the file names and their code after
user.h
#pragma once
#ifndef USER_H
#define USER_H
#include<cstring>
#include<iostream>
#pragma warning( disable : 4716 )
using namespace std;
class user
{
private:
string name;
int age;
int id;
string password;
string email;
public:
static int count;
void setName(string Name);
string getName();
void setPassword(string Password);
string getPassword();
void setEmail(string Email);
string getEmail();
void setAge(int Age);
int getAge();
void setId();
int getId();
user();
user(string Name, int Age, string Email, string Password);
user(const user& u);
bool operator ==(const user& u);
friend ostream& operator<<(ostream& output, const user& u);
friend istream& operator>>(istream& input, user& u);
};
#endif
user.cpp
#include "user.h"
void user::setName(string Name)
{
name = Name;
}
string user::getName()
{
return name;
}
void user::setPassword(string Password)
{
password = Password;
}
string user::getPassword()
{
return password;
}
void user::setEmail(string Email)
{
Email = email;
}
string user::getEmail()
{
return email;
}
void user::setAge(int Age)
{
age = Age;
}
int user::getAge()
{
return age;
}
void user::setId()
{
count++;
id = count;
}
int user::getId()
{
return id;
}
user::user()
{
age = 0;
name = password = email = "";
}
user::user(string Name, int Age, string Email, string Password)
{
name = Name;
password = Password;
email = Email;
age = Age;
}
user::user(const user& u)
{
name = u.name;
age = u.age;
email = u.email;
password = u.password;
id = u.id;
}
bool user::operator==(const user& u)
{
bool status;
if (name == u.name && age == u.age && email == u.email && id == u.id)
{
status = true;
}
else
{
status = false;
}
}
ostream& operator<<(ostream& output, const user& u)
{
output << endl << "User name :" << u.name << endl << "User id :" << u.id << endl << "User age :" << u.age << endl << "User email :" << u.email << endl << "User password :" << u.password << endl;
}
istream& operator>>(istream& input, user& u)
{
input >> u.name >> u.age >> u.email >> u.password;
}
Book.h
#pragma once
#ifndef BOOK_H
#define BOOK_H
#include<cstring>
#include<iostream>
#include "user.h"
#pragma warning( disable : 4716 )
using namespace std;
class Book
{
private:
string title;
string isbn;
int id;
string category;
double averageRating;
user author;
public:
static int count;
void setTitle(string Title);
string getTitle();
void setISBN(string ISBN);
string getISBN();
void setId();
int getId();
void setCategory(string Category);
string getCategory();
void setRating(double Rating);
double getRating();
void setAuthor(user User);
user getAuthor();
Book();
Book(const Book& b);
bool operator==(const Book& b);
friend ostream& operator<<(ostream& output, const Book& b);
friend istream& operator>>(istream& input, Book& b);
};
#endif
Book.cpp
#include "Book.h"
void Book::setTitle(string Title)
{
title = Title;
}
string Book::getTitle()
{
return title;
}
void Book::setISBN(string ISBN)
{
isbn = ISBN;
}
string Book::getISBN()
{
return isbn;
}
void Book::setId()
{
count++;
id = count;
}
int Book::getId()
{
return id;
}
void Book::setCategory(string Category)
{
category = Category;
}
string Book::getCategory()
{
return category;
}
void Book::setRating(double Rating)
{
averageRating = Rating;
}
double Book::getRating()
{
return averageRating;
}
void Book::setAuthor(user User)
{
author = User;
}
user Book::getAuthor()
{
return author;
}
Book::Book()
{
title = isbn = category = "";
averageRating = 0;
}
Book::Book(const Book& b)
{
title = b.title;
isbn = b.isbn;
category = b.category;
author = b.author;
id = b.id;
averageRating = b.averageRating;
}
bool Book::operator==(const Book& b)
{
bool status;
if (title == b.title && isbn == b.isbn && category == b.category && id == b.id && author == b.author)
{
status = true;
}
else
{
status = false;
}
}
ostream& operator<<(ostream& output, const Book& b)
{
output << endl << "Book title :" << b.title << endl << "Book ISBN :" << b.isbn << endl << "Book ID :" << b.id << endl << "Book category :" << b.category << endl << "Average rating :" << b.averageRating << endl;
}
istream& operator>>(istream& input, Book& b)
{
input >> b.title >> b.isbn >> b.category;
}
UserList.h
#pragma once
#include<cstring>
#include<iostream>
#include "user.h"
using namespace std;
class UserList
{
private:
user* users;
int capacity;
int usersCount;
public:
UserList(int Capacity);
void addUser(user user);
user& searchUserID(int id);
user& searchUserName(string name);
void deleteUser(int id);
friend ostream& operator<<(ostream& output, const UserList& userList);
~UserList();
};
UserList.cpp
#include "UserList.h"
UserList::UserList(int Capacity)
{
usersCount = 0;
capacity = Capacity;
user udef;
users = new user[capacity];
for (int i = 0; i < capacity; i++)
{
users[i] = udef;
}
}
void UserList::addUser(user newuser)
{
users[usersCount] = newuser;
usersCount++;
}
user& UserList::searchUserName(string name)
{
cout << "Enter the user's name" << endl;
cin >> name;
for (int i = 0; i < usersCount; i++)
{
if (name == users[i].getName())
{
cout << users[i];
}
else cout << "USER NOT FOUND !!!!" << endl;
}
}
user& UserList::searchUserID(int id)
{
cout << "Enter the user's ID" << endl;
cin >> id;
for (int i = 0; i < usersCount; i++)
{
if (id == users[i].getId())
{
cout << users[i];
}
else cout << "USER NOT FOUND !!!!" << endl;
}
}
void UserList::deleteUser(int id)
{
cout << "Enter the user's ID" << endl;
cin >> id;
int i;
for (i = 0; i < usersCount; i++)
{
if (id == users[i].getId())
{
break;
}
}
for (i; i < usersCount; i++)
{
users[i] = users[i + 1];
}
usersCount--;
}
ostream& operator<<(ostream& output, const UserList& userList)
{
for (int i = 0; i < userList.usersCount; i++)
{
output << "---- USER " << i + 1 << "----" << userList.users[i];
}
}
UserList::~UserList()
{
delete users;
}
main.cpp
#include<cstring>
#include<iostream>
#include "user.h"
#include "Book.h"
#include "UserList.h"
#pragma warning( disable : 4716 )
using namespace std;
int user::count = 0;
int Book::count = 0;
int main()
{
int size;
cout << "enter the size of the list" << endl;
cin >> size;
UserList ul1(size);
cout << ul1 << endl;
return 0;
}
There are several issues with your code.
In the UserList destructor:
delete users;
This is the wrong form of delete. This should be:
delete [] users;
Since new[] was used to allocate the array, delete [] must be used.
The other major issue that has to be fixed is this one in UserList:
ostream& operator<<(ostream& output, const UserList& userList)
You need to return output;, but your code fails to do so. Not returning a value from a function that has a return value invokes undefined behavior.
As a matter of fact, several of your functions require you to return values, yet you failed to do so. Thus any calls to those functions will result in undefined behavior.

I need help in entering two string in a class and getting its output

When I am trying to enter the two string name str1and str2 in program it is giving me error
cpp|19|error: cannot convert 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} to 'int' in return|
|26|error: cannot convert 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} to 'int' in return|
#include <iostream>
#include <sstream>
#include<string>
using namespace std;
class Student
{
string str1,str2;
public:
void set_first_name(string a)
{
str1=a;
}
int get_first_name()
{
return str1;
}
void set_last_name(string b){
str2=b;
}
int get_last_name()
{
return str2;
}
};
int main() {
string first_name, last_name;
cin >> first_name >> last_name ; //Entering the string
Student st;
st.set_first_name(first_name); //setting the string 1 in class Student
st.set_last_name(last_name); //setting the string 2 in class Student
cout << st.get_last_name() << ", " << st.get_first_name() << "\n"; // calling first and second string
cout << st.to_string(); //I don't know what
return 0;
}
new problem is
class Student
{
string str1,str2;
int ag, st;
public:
void set_first_name(string a)
{
str1=a;
}
string get_first_name()
{
return str1;
}
void set_last_name(string b){
str2=b;
}
string get_last_name()
{
return str2;
}
void set_age(int ag1)
{
ag=ag1;
}
int get_age(){
return ag;}
void set_standard(int st1){
st=st1;}
int get_standard(){
return st};
friend std::ostream& operator<<(std::ostream&, const Student&);
};
std::ostream& operator<<(std::ostream& out, const Student& student)
{
out << "("<<student.ag<<","<<student.str1 << "," << student.str2 << "," << student.st << ")";
return out;
}
int get_standard(void)
{
return st;
}
};
int main() {
int age, standard;
string first_name, last_name;
cin >> age >> first_name >> last_name >> standard;
Student st;
st.set_age(age);
st.set_standard(standard);
st.set_first_name(first_name);
st.set_last_name(last_name);
cout << st.get_age() << "\n";
cout << st.get_last_name() << ", " << st.get_first_name() << "\n";
cout << st.get_standard() << "\n";
cout << "\n";
std::cout << st;
return 0;
}
Errors are
error: expected ';' before '}' token
error: 'st' was not declared in this scope
error: expected declaration before '}' token
#include <iostream>
#include <sstream>
using namespace std;
class Student{
private:
int age;
int standard;
string first_name;
string last_name;
public:
void set_age(int a){
age = a;
}
int get_age(){
return age;
}
void set_standard(int b){
standard = b;
}
int get_standard(){
return standard;
}
void set_first_name(string c){
first_name = c;
}
string get_first_name(){
return first_name;
}
void set_last_name(string d){
last_name = d;
}
string get_last_name(){
return last_name;
}
string to_string()
{
stringstream ss;
char c = ',';
ss<<age<<c<<first_name<<c<<last_name<<c<<standard;
return ss.str();
}
};
int main() {
int age, standard;
string first_name, last_name;
cin >> age >> first_name >> last_name >> standard;
Student st;
st.set_age(age);
st.set_standard(standard);
st.set_first_name(first_name);
st.set_last_name(last_name);
cout << st.get_age() << "\n";
cout << st.get_last_name() << ", " << st.get_first_name() << "\n";
cout << st.get_standard() << "\n";
cout << "\n";
cout << st.to_string();
return 0;
}
That's because return type of getter functions is int instead of string:
string get_first_name()
{
return str1;
}
string get_last_name()
{
return str2;
}
Update: Answering to question from comments.
class Student
{
string str1,str2;
int age, st;
public:
void set_first_name(string a)
{
str1=a;
}
int get_first_name()
{
return str1;
}
void set_last_name(string b){
str2=b;
}
int get_last_name()
{
return str2;
}
friend std::ostream& operator<<(std::ostream&, const Student&);
};
std::ostream& operator<<(std::ostream& out, const Student& student)
{
out << "("<<student.age<<","<<student.str1 << "," << student.str2 << "," << student.st << ")";
return out;
}
Then you can do:
int main()
{
Student me;
std::cout << me;
}
In your first error case, you are trying to return std::string objects where int vales are expected. Your get_first_name() and get_last_name() getters need to return std::string instead of int, eg:
string get_first_name()
{
return str1;
}
string get_last_name()
{
return str2;
}
In your second error case, you have several syntax errors in your code. You have several syntax elements that are either missing or in the wrong places.
The code should look more like this instead:
class Student
{
std::string str1, str2;
int ag, st;
public:
void set_first_name(std::string a)
{
str1 = a;
}
std::string get_first_name() const // <-- add const here
{
return str1;
}
void set_last_name(std::string b)
{
str2 = b;
}
std::string get_last_name() const // <-- add const here
{
return str2;
}
void set_age(int ag1)
{
ag = ag1;
}
int get_age() const // <-- add const here
{
return ag;
}
void set_standard(int st1)
{
st = st1;
}
int get_standard() const // <-- add const here
{
return st; // <-- ; needed here!
} // <-- remove ; from here!
friend std::ostream& operator<<(std::ostream&, const Student&);
};
std::ostream& operator<<(std::ostream& out, const Student& student)
{
out << "(" << student.ag << "," << student.str1 << "," << student.str2 << "," << student.st << ")";
return out;
}
// <-- remove entire get_standard() from here!
// <-- remove }; from here!
int main()
{
int age, standard;
string first_name, last_name;
cin >> age >> first_name >> last_name >> standard;
Student st;
st.set_age(age);
st.set_standard(standard);
st.set_first_name(first_name);
st.set_last_name(last_name);
cout << st.get_age() << "\n";
cout << st.get_last_name() << ", " << st.get_first_name() << "\n";
cout << st.get_standard() << "\n";
cout << "\n";
std::cout << st;
return 0;
}
Return type of your functions is int, not string.

How would I operate overload "<<"?

My professor said operator overloading of << is optional here but I wanted to know how I could do it as I was only able to figure it out without using overloading.
This is a function in my code:
void listProducts()
{
//list all the available products.
cout << "Available products:\n";
for(int i=0; i<numProducts; i++)
cout << products[i]->getCode() << ": " << products[i]->getName() << " # "
<< products[i]->getPrice() << "/pound.\n";
}
And this is the product.cpp file:
Product :: Product(int code, string name, double price) {
this->code = code;
this->name = name;
this->price = price;
}
int Product:: getCode(){
return code;
}
string Product :: getName(){
return name;
}
double Product :: getPrice(){
return price;
}
You can do something like
std::ostream & operator<<(std::ostream &out,const classname &outval)
{
//output operation like out<<outval.code<<":"<<outval.name<<"#"<<outval.price;
return out;
}
and
friend std::ostream & operator<<(std::ostream &out,const classname &outval);
in your class to access private members.
If you understood the solution to your previous question this, then understanding the below code is very easy. The only difference is the usage of friend function about which you can read gfg link.
For your better understanding, the exact same example is given below,
#include <iostream>
using namespace std;
class Product
{
private:
int code; string name; double price;
public:
Product(int, string, double);
friend ostream & operator << (ostream &out, const Product &p);
};
Product :: Product(int code, string name, double price) {
this->code = code;
this->name = name;
this->price = price;
}
ostream & operator << (ostream &out, const Product &p)
{
out<< p.code << ": " << p.name << " # "
<< p.price << "/pound.\n";
return out;
}
int main()
{
Product book1(1256,"Into to programming", 256.50);
Product book2(1257,"Into to c++", 230.50);
cout<<book1<<endl<<book2;
return 0;
}

C++ Copy Constructor & Operator Overloading

I am relatively new to classes and was introduced to copy constructors and overloading last week. I am supposed to overload the = operator and use it to assign multiple variables using the class name.
For some reason, running the program causes a popup saying
program.cpp has stopped responding.
I am positive there are minor/major things that I am missing due to me being a rookie with objects in C++.
Any advice is very much appreciated!
#include<iostream>
#include<string>
using namespace std;
class Employee
{
private:
char *name;
string ID;
double salary;
public:
Employee() {}
Employee(char *name, string eid, double salary) {}
Employee(const Employee &obj)
{
name = new char;
ID = obj.ID;
salary = obj.salary;
}
~Employee() {}
void setName(char *n)
{
name = n;
}
void setID(string i)
{
ID = i;
}
void setSalary(double s)
{
salary = s;
}
char getName()
{
return *name;
}
string getID()
{
return ID;
}
double getSalary()
{
return salary;
}
Employee operator = (Employee &right)
{
delete[] name;
ID = right.ID;
salary = right.salary;
return *this;
}
};
int main()
{
Employee e1("John", "e222", 60000), e2(e1), e3, e4;
e3 = e4 = e2;
e2.setName("Michael");
e2.setSalary(75000);
e3.setName("Aaron");
e3.setSalary(63000);
e4.setName("Peter");
cout << "\nName: " << e1.getName() << "\nID: " << e1.getID() << "\nSalary: " << e1.getSalary() << endl;
cout << "\nName: " << e2.getName() << "\nID: " << e2.getID() << "\nSalary: " << e2.getSalary() << endl;
cout << "\nName: " << e3.getName() << "\nID: " << e3.getID() << "\nSalary: " << e3.getSalary() << endl;
cout << "\nName: " << e4.getName() << "\nID: " << e4.getID() << "\nSalary: " << e4.getSalary() << endl;
return 0;
}
There are several issues with this code.
The first issue is in the constructor Employee(char *name, string eid, double salary) {} which is just doing nothing and ignoring the passed data whereas it should be using it to initialize the fields (class member data).
Employee(char *name, string eid, double salary)
{
const size_t bufferSize = strlen(name) + 1;
this->name = new char[bufferSize];
memcpy(this->name, name, bufferSize);
this->ID = eid;
this->salary = salary;
}
The second issue is in the copy constructor Employee(const Employee &obj) , where you are just initializing the name (with single byte of char) and that's it. What the copy constructor suppose to do is initialize the fields (class members) of the class with the fields of the class object being passed to it.
Employee(const Employee &obj)
{
const size_t bufferSize = strlen(name) + 1;
this->name = new char[bufferSize];
memcpy(this->name, name, bufferSize);
ID = obj.ID;
salary = obj.salary;
}
the third issue is with the default constructor which is suppose to initialize the name pointer with the NULL so that the destructor could clean it up nicely:
Employee() : name(NULL) {}
~Employee()
{
if (NULL != name)
delete[] name;
}
the fourth and last problem is with the assignment operator that's suppose to properly initialize the name member data instead of deleting it (which doesn't make sense)
Employee operator = (Employee &right)
{
if (NULL != this->name)
delete[] this->name;
const size_t bufferSize = strlen(right.name) + 1;
this->name = new char[bufferSize];
memcpy(this->name, right.name, bufferSize);
ID = right.ID;
salary = right.salary;
return *this;
}
The problem is this line:
delete[] name;
You shouldn't delete anything you haven't allocated with new first. If you delete the above line, your program kind of works. :)
Here's a slightly revised version of your program that works:
#include<iostream>
#include<string>
using namespace std;
class Employee
{
private:
char *name;
string ID;
double salary;
public:
Employee() {}
Employee(char *name, string eid, double salary)
: name (name) // ADDED THESE
, ID(eid)
, salary(salary)
{
}
Employee(const Employee &obj)
{
name = obj.name; // WAS: new char;
ID = obj.ID;
salary = obj.salary;
}
~Employee() {}
void setName(char *n)
{
name = n;
}
void setID(string i)
{
ID = i;
}
void setSalary(double s)
{
salary = s;
}
char * getName()
{
return name;
}
string getID()
{
return ID;
}
double getSalary()
{
return salary;
}
Employee operator = (const Employee &right)
{
name = right.name; // WAS: delete[] name;
ID = right.ID;
salary = right.salary;
return *this;
}
};
int main()
{
Employee e1("John", "e222", 60000), e2(e1), e3, e4;
e3 = e4 = e2;
e2.setName("Michael");
e2.setSalary(75000);
e3.setName("Aaron");
e3.setSalary(63000);
e4.setName("Peter");
cout << "\nName: " << e1.getName() << "\nID: " << e1.getID() << "\nSalary: " << e1.getSalary() << endl;
cout << "\nName: " << e2.getName() << "\nID: " << e2.getID() << "\nSalary: " << e2.getSalary() << endl;
cout << "\nName: " << e3.getName() << "\nID: " << e3.getID() << "\nSalary: " << e3.getSalary() << endl;
cout << "\nName: " << e4.getName() << "\nID: " << e4.getID() << "\nSalary: " << e4.getSalary() << endl;
return 0;
}