In Interview, I asked to write constructor, Copy constructor and assignment operator. I wrote the following code.
He then asked me what is wrong in following code which I unable to answer, could you help me to know what is wrong?
Also, From question what interviewer was trying to find?
//constructor, copy constructor, assignment operator and destructor
class Employee
{
int id;
char *name;
public:
//constructor
Employee()
{
id=0;
*name = new char[];
}
//Copy constructor
Employee (const Employee& oldObj)
{
id = oldObj.id;
*name = *(oldObj.name);
}
//destructor
~Employee()
{
delete[] name;
}
//Assignment operator overloading
void operator = (const Employee& obj)
{
id = obj.id;
delete[] name;
*name = *(obj.name);
}
};
int main()
{
Employee a1;
Employee a2 = a1; //copy constructor
Employee a3;
a3 = a1;//assignment operator
}
what is wrong in following code
Using bare owning pointers instead of smart pointers or containers.
*name = pointer is ill-formed.
new char[] is ill-formed.
I got this copy constructor from a book and added the cout to compare the values:
Person::Person(const Person& c) {
m_pName = new string(*(c.m_pName));
m_Age = c.m_Age;
cout << m_pName << " " << &m_pName;
}
The cout will output 2 different addresses. The book I'm reading doesn't define what the m_pName is on its own without the &, it only says that &m_pName is the heap member address. What is the address returned without the & operator?
edit: Here is the class and constructor:
class Person() {
public:
Person(const string& name = 0);
Person(const Person& c);
private:
string* m_pName;
}
Person::Person(const string& name) {
m_pName = new string(name);
}
From the snippet you've provided it looks like m_pName is a pointer to string (to an std::string perhaps), so m_pName without an ampersand is the address of that string, just allocated.
#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.
I have a class:
class Person{
public:
Person();
~Person();
string name;
int* age;
};
int main()
{
Person* personOne = new Person;
personOne->name = "Foo";
personOne->age = new int(10);
return 0;
}
How do I create another object of Person that copies all of personOne data? The age pointer needs to be pointing to a new int so whenever the age changes in personOne or personTwo, it doesn't affect each other.
There are two posibilites:
copy constructor + assignment operator
clone method
Code:
class Person{
public:
Person();
~Person();
Person (const Person& other) : name(other.name), age(new int(*(other.age)))
{
}
Person& operator = (const Person& other)
{
name = other.name;
delete age; //in case it was already allocated
age = new int(*(other.age))
return *this;
}
//alternatively
Person clone()
{
Person p;
p.name = name;
p.age = new int(age);
return p;
}
string name;
int* age;
};
Answer these before going forward:
do you really need an int pointer?
are you aware of smart pointers?
do you free all memory you allocate?
do you initialize all members in the constructor?
I'm fairly noobish at C++, but very comfortable with pointers, dereferencing, etc. I'm having a problem with my overload of the << operator for a class, in that it compiles fine but crashes when run. It feels like an infinite loop, but I'm not certain. Here's the code, and any help is appreciated.
#include <string>
#include <iostream>
using namespace std;
class Person
{
private:
string _name;
Person* _manager;
public:
Person(string name, Person *manager);
Person(string name);
friend ostream &operator<<(ostream &stream, Person &p);
};
Person::Person(string name, Person *manager)
{
_name = name;
_manager = manager;
}
Person::Person(string name)
{
_name = name;
}
ostream &operator<<(ostream &stream, Person &p)
{
Person* mgr = p._manager;
stream << p._name << std::endl;
stream << mgr->_name << std::endl;
return stream;
}
int main()
{
Person *pEmployee = new Person("John Doe Employee");
Person *pManager = new Person("John Doe Manager", pEmployee);
cout << *pEmployee;
cout << *pManager;
return 0;
}
In your constructor with just a single argument, you need to set _manager to NULL/0. Test for this in your operator<< and don't output mgr->name if it is NULL/0. As it stands, you are dereferencing an uninitialised pointer.
Person::Person(string name)
{
_name = name;
_manager = 0;
}
ostream &operator<<(ostream &stream, Person &p)
{
Person* mgr = p._manager;
stream << p._name << std::endl;
if (mgr)
stream << mgr->_name << std::endl;
return stream;
}
There are a number of other things you could do better, such as using const references on arguments and using the constructor initialiser list, but they wont be the cause of your problem. You should also address ownership issues with the manager object you pass in to the constructor to ensure it does not get double-deleted.
your _manager pointer is not initialized upon constructing the first Person instance, hence referencing p._manager in your operator << crashes.
Besides that, you have a memory leak since you call new but not delete.
Your implementation of operator<< does not check if the _manager member is valid. If there is no manager, you should make this explicit by setting the pointer to 0. Otherwise the pointer value is undefined and accessing it will crash your program.
(1) Your Person class should set _manager to 0 (null pointer) if none is supplied in the constructor:
Person::Person(string name) : _name(name), _manager(0)
{
}
(2) In your operator<<, check the pointer before dereferencing it:
if (mgr) {
stream << mgr->_name << std::endl;
}
Some hints for better code:
(1) Change your function arguments to accept const string& instead of string. This way, the string is not copied when calling the function/constructor, but passed as a constant reference.
(2) It is cleaner to let your operator<< accept a const reference for the Person as well, since it does not/should not modify the Person. This way, you can use the operator also in places where you have a constant Person.
Person::Person(string name)
{
_name = name;
}
Who is your manager?
Person::Person(string name) : _manager(NULL)
{
_name = name;
}
ostream &operator<<(ostream &stream, Person &p)
{
Person* mgr = p._manager;
stream << p._name << std::endl;
if (mgr != NULL) { stream << mgr->_name << std::endl; }
return stream;
}
Your Person instance *pEmployee does not have the _manager set. This may be a NULL pointer.