c++ destructor called before cout - c++

#include <iostream>
#include <string.h>
using namespace std;
class Location
{
double lat, lon;
char *emi;
public:
Location(int =0, int=0, const char* =NULL);
~Location();
Location (const Location&);
void print () const;
friend ostream& operator<< (ostream&, const Location &);
void operator! ();
protected: ;
private:
};
Location::Location(int lat, int lon, const char *emi)
{
this->lat=lat;
this->lon=lon;
if (emi!=NULL)
{
this->emi=new char [strlen (emi)+1];
strcpy (this->emi, emi);
}
}
Location::~Location()
{
if (emi!=NULL)
delete []emi;
}
Location::Location(const Location &l)
{
lat=l.lat;
lon=l.lon;
if (l.emi!=NULL)
{
emi=new char [strlen (l.emi)+1];
strcpy (emi, l.emi);
}
}
void Location::operator! ()
{
if (!(strcmp(this->emi, "north")))
strcpy (this->emi, "south");
else strcpy (this->emi, "north");
}
void Location::print() const
{
cout<<this->emi<<endl;
cout<<this->lon<<endl;
cout<<this->lat<<endl;
cout<<endl;
}
class Adress
{
char *des;
Location l1;
char *country;
public:
Adress(char *,const Location &, char *);
virtual ~Adress();
friend ostream& operator<< (ostream&, const Adress &);
protected:
private:
};
Adress::Adress(char *des,const Location &l1, char *country)
{
if (des!=NULL)
{
this->des=new char [strlen (des)+1];
strcpy (this->des, des);
}
if (country!=NULL)
{
this->country=new char [strlen (country)+1];
strcpy (this->country, country);
}
this->l1=l1;
}
Adress::~Adress()
{
if (country!=NULL)
delete []country;
if (des!=NULL)
delete []des;
}
ostream& operator<< (ostream &os, const Adress& a){
os <<"Descrition: " << a.des<<endl;
os<<"Country: "<<a.country<<endl;
a.l1.print();
return os;
}
int main ()
{
Adress a1 ("dsad", Location (323, 34, "fdsf"), "fsdf");
cout<<a1;
}
The problem is that when I create an Adress object and display it, all the fields are correct , but the "emi" which is messed up, showing a random character. I think the destructor is called before I display it. If I remove the Location destructor it works. How should I resolve it? I'm sorry for my mistakes but I am a newbie.

First of all, it would be better to use std::string rather than char* but I will explain your problem for the education goal.
You must ensure after constructing an object, all of its member variables are initialized. In the case of Location class for example; you did not initialize the emi member variable if the third argument of the constructor is nullptr. so I changed it a little:
Location::Location(int _lat, int _lon, const char* _emi)
: lat(_lat)
, lon(_lon)
, emi(nullptr)
{
if (_emi != nullptr)
{
emi = new char[strlen(_emi) + 1];
strcpy(emi, _emi);
}
}
Next, you have a raw pointer in your class and you can not simply copy or assign it. You have to implement the assignment operator as well as the copy constructor.
Location& Location::operator=(const Location& other)
{
if (this != &other)
{
lat = other.lat;
lon = other.lon;
if (emi) delete[] emi;
emi = new char[strlen(other.emi) + 1];
strcpy(emi, other.emi);
}
return *this;
}

Related

How to write/read classes within classes to binary file C++

I'm working on a project where I have to write a class that contains three other classes as private member variables to a binary file, where it can then be read back into variables to be used in the code. The code writes to the file, but I don't know if it is writing the correct info as when I try to read the file it reads in junk. I have included my current setup, does this look correct? If so, what could be going wrong, and if not, how can I fix this?
If you need me to add any extra code, please ask. Another consideration is that two of the classes being used as member functions for the players objects inherit from other classes.
if (cFile.is_open())
{
cFile.seekp(ios::beg);
for (int i = 0; i < 3; i++)
{
cFile.write(reinterpret_cast<char *>(&players[i]), sizeof(Character));
}
cFile.seekg(ios::beg);
for (int i = 0; i < 3; i++)
{
cFile.read(reinterpret_cast<char *>(&playersRead[i]), sizeof(Character));
playersRead[i].display();
}
cFile.close();
}
else
{
cout << "Error opening file." << endl;
}
I've been working on this code for a few days and am really having trouble. I appreciate any help I can get, thanks in advance.
#pragma once
#include <iostream>
using std::ostream;
#include "string.h"
#include "coinPouch.h"
#include "backpack.h"
class Character
{
public:
Character();
Character(String name);
Character(String name, CoinPouch wallet, Backpack storage);
Character(const Character & copy);
~Character();
Character & operator =(const Character & rhs);
friend ostream & operator << (ostream & out, const Character & c);
void purchase(int p, int g, int s, int c);
void income(int p, int g, int s, int c);
void addPotion(const Potion & toAdd);
void checkBalance();
void checkBackpack();
void changeName(const String & newN);
void display();
String getName();
CoinPouch getWallet();
Backpack getStorage();
void setName(String name);
void setWallet(CoinPouch wallet);
void setStorage(Backpack storage);
private:
String m_name;
CoinPouch m_wallet;
Backpack m_storage;
};
#include "character.h"
using std::endl;
using std::cout;
Character::Character() : m_name("Player")
{
CoinPouch initialW;
Backpack initialS;
m_wallet = initialW;
m_storage = initialS;
}
Character::Character(String name) : m_name(name)
{
CoinPouch initialW;
Backpack initialS;
m_wallet = initialW;
m_storage = initialS;
}
Character::Character(String name, CoinPouch wallet, Backpack storage) : m_name(name), m_wallet(wallet), m_storage(storage)
{
}
Character::Character(const Character & copy) : m_name(copy.m_name), m_wallet(copy.m_wallet), m_storage(copy.m_storage)
{
}
Character::~Character()
{
}
Character & Character::operator =(const Character & rhs)
{
if (this != &rhs)
{
m_name = rhs.m_name;
m_wallet = rhs.m_wallet;
m_storage = rhs.m_storage;
}
return *this;
}
ostream & operator << (ostream & out, const Character & c)
{
out << c.m_name << ": " << endl;
out << c.m_wallet << endl;
out << c.m_storage << endl;
return out;
}
void Character::purchase(int p, int g, int s, int c)
{
m_wallet.buy(p, g, s, c);
}
void Character::income(int p, int g, int s, int c)
{
m_wallet.add(p, g, s, c);
}
void Character::addPotion(const Potion & toAdd)
{
m_storage.addPotion(toAdd);
}
void Character::checkBalance()
{
m_wallet.display();
}
void Character::checkBackpack()
{
m_storage.displayContents();
}
void Character::changeName(const String & newN)
{
m_name = newN;
}
void Character::display()
{
cout << m_name << ": " << endl;
m_wallet.display();
m_storage.displayContents();
}
String Character::getName()
{
return m_name;
}
CoinPouch Character::getWallet()
{
return m_wallet;
}
Backpack Character::getStorage()
{
return m_storage;
}
void Character::setName(String name)
{
m_name = name;
}
void Character::setWallet(CoinPouch wallet)
{
m_wallet = wallet;
}
void Character::setStorage(Backpack storage)
{
m_storage = storage;
}
#pragma once
#include <iostream>
using std::ostream;
#include "string.h"
class CoinPouch
{
public:
CoinPouch();
CoinPouch(String init);
CoinPouch(int p, int g, int s, int c);
CoinPouch(const CoinPouch & copy);
~CoinPouch();
CoinPouch & operator = (const CoinPouch & rhs);
friend ostream & operator << (ostream & out, const CoinPouch & c);
void add(int p, int g, int s, int c);
bool checkCost(int p, int g, int s, int c);
void buy(int p, int g, int s, int c);
void convertCost();
void roundUp();
void display();
int getP();
int getG();
int getS();
int getC();
private:
String m_amount;
int m_platinum;
int m_gold;
int m_silver;
int m_copper;
};
#pragma once
#include "potions.h"
class DynamicArray
{
public:
// Constructors
DynamicArray();
~DynamicArray();
DynamicArray(const DynamicArray & copy);
// Op Equals
DynamicArray & operator =(const DynamicArray & rhs);
// Insert, delete, and get elements functions
int getElements();
void Insert(const Potion & add);
void Delete(const Potion & rmv);
void display();
// Overloaded operators
Potion & operator [](int index);
friend ostream & operator << (ostream & out, const DynamicArray & d);
private:
// Member variables
Potion * m_array;
int m_elements;
// Find function
int Find(const Potion & target);
};
#pragma once
#include "string.h"
#include <iostream>
using std::ostream;
class Potion
{
public:
// Constructors
Potion();
Potion(String name, String description, String potency, String cost);
Potion & operator = (const Potion & rhs);
Potion(const Potion & copy);
// Desctructor
~Potion();
// Overloaded operators
bool operator == (const Potion & rhs) const;
friend ostream & operator << (ostream & out, const Potion & p);
// Getter functions
String getName();
String getDesc();
String getPotency();
String getCost();
int getP();
int getG();
int getS();
int getC();
// Setter functions
void setName(String name);
void setDesc(String desc);
void setPotency(String potency);
void setCost(String cost);
// Convert and display functions
void convertCost();
void display();
private:
// Strings to hold item information
String m_name;
String m_description;
String m_potency;
String m_cost;
// Ints to hold cost information
int m_platinum;
int m_gold;
int m_silver;
int m_copper;
// Logical test
bool m_isnull = false;
};
#pragma once
#include <iostream>
using std::ostream;
class String
{
public:
// Constructors
String();
String(char ch);
String(const char * str);
// Destructor
~String();
// Copy Constructor and Copy Assignment Constructor
String(const String & copy);
String & operator=(const String & rhs);
friend ostream & operator << (ostream & out, const String & s);
// Added Functionality
void display();
void upper();
void lower();
// Operator Conversion
operator char *();
operator const char *();
// Overloaded operator
bool operator == (const String & rhs) const;
private:
// Member variables
char * m_str;
int m_ischar;
};
#pragma once
#include "dynamicarray.h"
#include "coinPouch.h"
#include "string.h"
class Backpack
{
public:
Backpack();
Backpack(DynamicArray potions);
Backpack(const Backpack & copy);
~Backpack();
Backpack & operator = (const Backpack & rhs);
friend ostream & operator << (ostream & out, const Backpack & c);
void addPotion(const Potion & add);
void usePotion(const Potion & rm);
void displayContents();
private:
DynamicArray m_potions;
int m_number;
};
This is a school project, and I am supposed to write the Character class to a binary file in order to save the characters so I can load them in on the program start. Right now I'm just trying to make sure that they can be successfully written to and read from the binary file and I have had no luck.
My bad, didn't know what to post and I didn't want to post everything in my file. Here is the character class. Let me know what else is needed, if anything.
It should be immediately obvious that this code can't possibly work.
cFile.write(reinterpret_cast<char *>(&players[i]), sizeof(Character));
However big sizeof(Character) is, we could have a Character with an m_name that takes up more bytes than that. So this code can't possibly be writing the character's name, and it clearly needs to do that.
Before you write anything to a file, decide on (and ideally, document) a file format at the byte level. Make sure your code writes in the format you documented and also can read in the format you documented. Skipping this step leads to pain and it also makes debugging impossible because you can't look at the file and compare it to a specification to see whether the writer or the reader is at fault.
Had you documented what bytes the player's name will occupy in the file, you'd immediately realize that you either need to have a variable-length object and encode the length somehow or pick a largest size name and allocate those many bytes. But because you skipped that vital step, you never actually worked out how to write a Character to a file.

Overloading the operator=? c++

I having a trouble trying to insert an object from a class that I created to a char. I create a class name Element as part of a bigger program, but when I try to overloading operator= so that i can get in char variable the char I got in the Element obj nothing work...
Element.h
class Element {
private:
char val;
public:
Element();
Element(char newVal); //check input - throw execption
~Element();
friend ostream& operator<<(ostream& os, const Element& obj);
void setElement(char newVal);
char getElement();
void operator= (const Element newVal);
void operator= (char newVal);
};
Element.cpp
#include "Element.h"
Element::Element()
{
val ='.';
}
Element::Element(char newVal)
{
if (newVal!='X' && newVal!='O'&& newVal!='.'){
inputExecption error;
error.what();
} else{
val=newVal;
}
}
Element::~Element()
{
}
void Element::setElement(char newVal)
{
if (newVal!='X' && newVal!='O'&& newVal!='.'){
inputExecption error;
error.what();
} else{
val=newVal;
}
}
char Element::getElement()
{
return val;
}
ostream& operator<<(ostream& os, const Element& obj)
{
return os << obj.val;
}
void Element::operator= (const Element Value){
val = Value.val;
}
void Element::operator= (char newVal){
if(val != 'X' && val != 'O'){
inputExecption a;
a.what();
}
val = newVal;
}
So as I said, what i'm trying to do is:
Element x='X';
char c = x; //(c=x.val)
cout<<c<<endl;//Will print X
thx! :)
In other words you're trying to convert an object of type Element to an object of type char. You can use a conversion operator for this:
class Element {
// ...
operator char() const { return val; }
};
The assignment operator only works when an instance of Element is used on the left hand side of the assignment.
IMHO, writing an implicit conversion operator (as 0x499602D2 suggested) is not the best idea.
For example, assume you have two separate file something like this:
//File char_utils.hh
#include <iostream>
void accept(char character) { std::cout <<"character: " <<character <<'\n'; }
//File elements_utils.hh
#include <iostream>
void accept(Element const& element) {
std::cout <<"element.getVal(): " <<element.getVal() <<'\n';
}
Then, depending on what you include in your implementation file (char_utils.hh or elements_utils.hh) you will get different behaviour, which may lead to many subtle bugs and/or interesting behaviours. ;)
This can be overcome by declaring conversion operator explicit, i.e.,
explicit operator char() const { return val; }
In such a case, you just need to:
Element e{'x'};
char c = static_cast<char>(e);
which shows the intent more clearly.
However, why do you need using an implicit conversion at all? Especially when you can use Element::getElement()? And if I may suggest, I would use different namin, e.g., Element::getValue(). Element::getElement() is very confusing.
Further reading: https://stackoverflow.com/a/16615725/1877420

Member object of another class

I have two classes: Location and Adress. Adress contains a member named l1 which is of the type Location.
class Location
{
double lat, lon;
char *em;
public:
Location(int =0, int=0, const char* =NULL);
~Location();
Location (const Location&);
friend ostream& operator<< (ostream&, const Location &);
};
class Adress
{
char *des;
Location l1;
char *country;
public:
Adress(char *,Location &, char *);
virtual ~Adress();
friend ostream& operator<< (ostream&, const Adress &);
};
Adress constructor:
Adress::Adress(char *des, Location &l1, char *country)
{
if (des!=NULL)
{
this->des=new char [strlen (des)+1];
strcpy (this->des, des);
}
if (country!=NULL)
{
this->country=new char [strlen (country)+1];
strcpy (this->country, country);
}
}
Location constructor:
Location::Location(int lat, int long, const char *em)
{
this->lat=lat;
this->lon=lon;
if (emi!=NULL)
{
this->em=new char [strlen (em)+1];
strcpy (this->em, em);
}
}
What I want to do is when I call the constructor of the class Location in the main function for creating a new object to automatically call the constructor of the location class, something like: Address ("desc", l1 (43.23, 32.12, "south"), "country"). I have tried in many ways but none of them seems to work. Sorry for my mistakes, I'm a begginer.
It seems you want to pass temporary location object to Address constructor so your parameterized constructor definition should be changed to accept const Location& and here is sample code for what you want to achieve :
class Location
{
double lat, lon;
char *em;
public:
Location(int =0, int=0, const char* =NULL);
~Location();
Location (const Location&);
friend ostream& operator<< (ostream&, const Location &);
protected:
private:
};
class Adress
{
char *des;
Location l1;
char *country;
public:
Adress(char *,const Location &, char *);
virtual ~Adress();
friend ostream& operator<< (ostream&, const Adress &);
protected:
private:
};
Adress::Adress(char *des, const Location &l1, char *country)
{
if (des!=NULL)
{
this->des=new char [strlen (des)+1];
strcpy (this->des, des);
}
if (country!=NULL)
{
this->country=new char [strlen (country)+1];
strcpy (this->country, country);
}
}
Location::Location(int lat, int lon, const char *em)
{
this->lat=lat;
this->lon=lon;
if (em!=NULL)
{
this->em=new char [strlen (em)+1];
strcpy (this->em, em);
}
}
int main()
{
Adress ("desc", Location (43.23, 32.12, "south"), "country");
return 0;
}
Also you cannot call class constructor with object name so l1 should be changed to class name i.e Location
Using struct, you can use brace-initialization, which follows the order of your variable declaration inside the struct.
struct Location
{
double lat, lon;
char *em;
};
struct Address
{
char *des;
Location l1;
char *country;
};
Address address {"My address", Location{188.0, 188.0, "1 em"}, "USA"};
std::cout << address.l1.lat << ", " << address.l1.lon ; // 188.0, 188.0

How do you get a + overload to become recognised in another file C++?

Just started learning C++ recently and I'm attempting to make my own string class from scratch. I'm currently working on concatenating strings by overloading += and + operators. After reading this article, basic-rules-of-operator-overloading, I have come up with the following implementation;
String & String::operator+=(const String &o)
{
char * newBuffer = new char[this->size() + o.size() - 1];
//copy over 'this' string to the new buffer
int index = 0;
while (this->at(index) != 0x0)
{
*(newBuffer + index) = this->at(index);
index++;
}
//copy over the param string into the buffer with the offset
//of the length of the string that's allready in the buffer
int secondIndex = 0;
while (o.at(secondIndex) != 0x0)
{
*(newBuffer + index + secondIndex) = o.at(secondIndex);
secondIndex++;
}
//include the trailing null
*(newBuffer + index + secondIndex) = 0x0;
//de-allocate the current string buffer and replace it with newBuffer
delete[] this->s;
this->s = newBuffer;
this->n = index + secondIndex;
return *this;
}
inline String operator+(String lhs, const String &rhs)
{
lhs += rhs;
return lhs;
}
However, the compiler will not recognise the + overload! It does work if I place the function in the main test file (where I am calling the method) but not if I place it in my String.cpp file where all my other methods are located.
Here is my String.h file if you need it;
#include <iostream>
class String
{
public:
String(const char * s);
String(const String &o);
int size() const;
char at(int i) const;
String &operator+=(const String &o);
private:
char * s;
int n;
//needs to be a friend function defined OUTSIDE of the class as when using
//ostream << String you do not have access to the ostream so they can't be
//member operators
friend std::ostream & operator<<(std::ostream &os, const String &o);
};
Thanks for any help!
(also, anything you think I can improve on in regards to my implementation would be graciously received)
Well everyone already explained, so it should be as simple as just adding the forward declaration to the end of your .h file like this:
#include <iostream>
class String
{
public:
String(const char * s);
String(const String &o);
int size() const;
char at(int i) const;
String &operator+=(const String &o);
private:
char * s;
int n;
//needs to be a friend function defined OUTSIDE of the class as when using
//ostream << String you do not have access to the ostream so they can't be
//member operators
friend std::ostream & operator<<(std::ostream &os, const String &o);
};
//forward declaration
String operator+(String lhs, const String &rhs);
The forward declaration just tells the compiler to look for a function with that signature. When it doesn't find it in your current .cpp file it looks up on the other .cpp files. I hope this helps!

C++ class destructor not working properly

#include<iostream>
#include<cstring>
using namespace std;
class Animal
{
protected:
int age;
char* name;
public:
Animal()
{
name=new char[1];
age = 0;
strcpy(name," ");
}
Animal(int _age, char* _name)
{
age=_age;
name = new char[strlen(_name)+1];
strcpy(name, _name);
}
~Animal()
{
delete[] name;
}
friend istream& operator >>(istream& in, Animal& a);
friend ostream& operator <<(ostream& out, const Animal& a);
};
istream& operator >>(istream& in, Animal& a)
{
in>>a.name>>a.age;
return in;
}
ostream& operator <<(ostream& out, const Animal& a)
{
out<<a.name<<a.age;
return out;
}
int main()
{
Animal a;
cin>>a;
cout<<a;
return 0;
}
This piece of code gives me the opportunity to enter a, then prints it and then the screen freezes and stops working. If I delete the destructor, it works properly. Why is this happening? And is it because of the destructor really?
You allocate a C-string having the size 1 and copy the C-string " " having the size 2 to it. Also you read an unknown amount of characters to the name in 'istream& operator >>(istream& in, Animal& a)`. Both will corrupt the memory the name is pointing to and both can be easily fix by using std::string:
class Animal
{
protected:
int age;
std::string name;
public:
Animal()
: age(0)
{}
Animal(int age_, std::string name_)
: age(age_), name(name_)
{}
};
This avoids writing a destructor and copy-constructor and assignment operator, which are missing in your code (See: Rule of three).
If you really don't want to use std::string, your best bet is something in the line of (live at coliru):
#include<iostream>
#include<cstring>
using namespace std;
class Animal {
private:
// copy a string
inline static char* dstr(const char* string) {
if( !string ) return NULL;
size_t l = strlen(string);
if( !l ) return NULL;
return strcpy(new char[++l], string);
}
protected:
int age;
char* name;
public:
// initialize an "empty" Animal
Animal() : age(0), name(NULL) {}
// initialize an animal by age and name
Animal(int _age, const char* _name): age(_age), name(dstr(_name)) {}
// initialize an animal from another animal:
// copy the name string
Animal(const Animal& _a): age(_a.age), name(dstr(_a.name)) {}
// assign an animal from another animal:
// first delete the string you have, then copy the string
Animal& operator=(const Animal& _a) {
// for exception-safety, save the old "name" pointer,
// then try to allocate a new one; if it throws, nothing happens
// to *this...
char* oldname = name;
name = dstr(_a.name);
age = _a.age;
delete[] oldname;
return *this;
}
// if C++11
// we have something called "move" constructor and assignment
// these are used, for instance, in "operator>>" below
// and they assume that _a will soon be deleted
Animal(Animal&& _a): Animal() {
swap(age, _a.age);
swap(name, _a.name);
}
Animal& operator=(Animal&& _a) {
swap(age, _a.age);
swap(name, _a.name);
return *this;
}
~Animal() { delete[] name; }
friend ostream& operator <<(ostream& out, const Animal& a);
};
istream& operator >>(istream& in, Animal& a) {
const size_t MAX_ANIMAL_NAME = 2048;
int age;
char n[MAX_ANIMAL_NAME+1];
if( in.getline(n, MAX_ANIMAL_NAME) >> age )
a = Animal(age, n);
return in;
}
ostream& operator <<(ostream& out, const Animal& a) {
return out<<a.name<<endl<<a.age<<endl;
}
int main() {
Animal a { 23, "bobo" };
cout<<a;
cin>>a;
cout<<a;
}
This does not leak memory, does not have undefined behaviours, and does not have buffer overruns.
You can also segregate the "need to manage memory" to a separate class:
#include<iostream>
#include<cstring>
using namespace std;
class AnimalName {
private:
char *n;
inline static char* dstr(const char* string) {
if( !string ) return NULL;
size_t l = strlen(string);
if( !l ) return NULL;
return strcpy(new char[++l], string);
}
public:
AnimalName() : AnimalName(NULL) {}
AnimalName(const char *_n) : n(dstr(_n)) {}
AnimalName(const AnimalName& _n) : n(dstr(_n.n)) {}
// see exception-safety issue above
AnimalName& operator=(const AnimalName& _n) { char *on = n; n = dstr(_n.n); delete[] on; return *this; }
AnimalName(AnimalName&& _n) : AnimalName() { swap(n, _n.n); }
AnimalName& operator=(AnimalName&& _n) { swap(n, _n.n); return *this; }
~AnimalName() { delete[] n; }
operator const char*() const { return n; }
friend istream& operator>>(istream& i, AnimalName& n) {
const size_t MAX_ANIMAL_NAME = 2048;
char name[MAX_ANIMAL_NAME+1];
if( i.getline(name, MAX_ANIMAL_NAME) )
n = name;
return i;
}
};
class Animal {
protected:
int age;
AnimalName name;
public:
// initialize an "empty" Animal
Animal() : age(0) {}
// initialize an animal by age and name
Animal(int _age, const char* _name): age(_age), name(_name) {}
friend ostream& operator <<(ostream& out, const Animal& a) {
return out<<a.name<<endl<<a.age<<endl;
}
};
istream& operator >>(istream& in, Animal& a) {
AnimalName n;
int age;
if( in >> n >> age )
a = Animal(age, n);
return in;
}
int main() {
Animal a { 23, "bobo" };
cout<<a;
cin>>a;
cout<<a;
return 0;
}
This way you get to follow the "rule of zero" (basically, classes that do not have the sole responsibility of managing memory/resources should not manage memory and therefore should not implement copy/move-constructors, assignments, or destructors.)
And that takes us to the real reason why you should use std::string: it not only does the memory management for you, but it also takes good care of your IO needs, eliminating the need for a "maximum animal name" in your example:
#include<iostream>
#include<string>
using namespace std;
class Animal {
protected:
string name; // name first, for exception-safety on auto-gen assignment?
int age;
public:
// initialize an "empty" Animal
Animal() : age(0) {}
// initialize an animal by age and name
Animal(int _age, const string& _name): age(_age), name(_name) {}
friend ostream& operator <<(ostream& out, const Animal& a) {
return out<<a.name<<endl<<a.age<<endl;
}
};
istream& operator >>(istream& in, Animal& a) {
string n;
int age;
if( getline(in, n) >> age )
a = Animal(age, n);
return in;
}
int main() {
Animal a { 23, "bobo" };
cout<<a;
cin>>a;
cout<<a;
}
A simple fix is to use std::string for your strings.
It almost doesn't matter what the specific errors you get are. But just to cover that, already in the constructor of Animal,
Animal()
{
name=new char[1];
age = 0;
strcpy(name," ");
}
you have Undefined Behavior by allocating just a single element array and then using strcpy top copy two char values there. Overwriting some memory after the array.
Then in operator>> the UB trend continues.
And so forth.
Use std::string.
Your memory management is wrong, which is corrupting the memory. You are allocating space for one character for name. But
strcpy(name," ");
will pass beyond the memory you allocated, since cstring is null terminated, it will put actually two character, effectively corrupting your memory ( you are accessing memory that is not allocated by your program). It itself has undefined behavior.
Further you are deleting an apparently unknown amount of memory in the destructor, which has also undefined behavior.
There are several bugs in your code.
The first one is in the constructor
Animal()
{
name=new char[1];
age = 0;
strcpy(name," ");
}
String literal " " consists from two characters: the space character and the terminating zero '\0;. So you need to allocate dynamically 2 bytes
name=new char[2];
that to use after that function strcpy.
Or instead of string literal " " you should use "an empty" string literal "" that contains only the terminating zero '\0'.
The other bug in function
istream& operator >>(istream& in, Animal& a)
{
in>>a.name>>a.age;
return in;
}
As you initially allocated only 1 byte pointed to by name then you may not use operator
in>>a.name;
because you will overwrite memory that does not belong to the allocated extent.
For example you could define the operator the following way
std::istream& operator >>( std::istream& in, Animal &a )
{
char itsName[25];
in >> itsName >> a.age;
char *tmp = new char[std::strlen( itsName ) + 1];
std::strcpy( tmp, itsName );
delete [] name;
name = tmp;
return in;
}
In this case you could enter a name that does not exceed 24 characters.
Take into account that you need also to define a copy constructor and the copy assignment operator if you are going to assign one object to another.