Re: Can anyone find the errors?
spacebebop@gmail.com wrote:
#include <cstring>
#include <iostream>
using namespace std;
class X
{
public:
X();
X( char * );
X(char const);
~X();
void print();
void print() const;
private:
char *_str;
};
class Y : public X
{
public:
Y();
Y( char * );
Y(char const *);
~Y();
void print();
void print() const;
private:
char *_str;
Hint: You already have a _str in X
};
X::X()
{
static char *str = "X's str empty";
static char str[] = "X's str empty";
_str = new char[ strlen( str ) ];
_str = new char[sizeof str];
strcpy(_str, str);
This copies strlen(str) + 1 characters! strlen() does not count the
terminating zero.
Why don't you use the std::string class?
cout << "X(), '" << str << "'\n";
}
X::X( char *str )
X::X(char const *str)
{
_str = new char[ strlen( str ) ];
_str = new char[strlen(str) + 1];
strcpy(str, str );
cout << "X(char *), '" << str << "'\n";
}
X::~X()
{
cout << "~X(), deallocating '" << _str << "'\n";
delete _str;
}
void X::print()
void X::print() const
{
cout << "X::print():\t'" << _str << "'\n";
}
Y::Y()
X::X() is called here. If you do not want this, you could do:
: X("Y's str empty")
[snip almost equal code]
int main()
{
X *x[3];
x[0] = new X( "X's data-index 0" );
x[1] = new Y( "Y's data-index 1" );
// Y y( "y's data-index 2" );
// x[2] = new Y( y );
x[0]->print();
x[1]->print();
This shall print "X::print()\tX's str empty\n"
http://www.parashift.com/c++-faq-lite/virtual-functions.html
// x[2]->print();
delete x[0];
delete x[1];
This line is undefined behaviour:
http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.7
// delete x[2];
return 0;
}
--
rbh