ali wrote:
Hi,
I'm have a base class with a virual function toString. All the derived
classes will have to implement this function.
Here's the code I have used:
//in base.h
virtual string* toString();
class base {
public:
virtual string toString() const = 0; // note: returns object not
// pointer. pure virtual
// requires derived
// classes to implement};
//in base.cpp
string* base::toString()
{
return new string("Error: using base class toString method");
}
implementation should be deleted. By making toString() pure virtual,
you can't call it through the base class, you can't even instantiate
an object that doesn't have an overridden toString().
//in main.cpp
base b;
above is now illegal, assuming the pure virtual. Implement derived
class derived : public base
{
public:
string toString() const { /* some implementation */ }};
derived d;
cout<<*(base.toString()<<endl;
The pointer construct is not necessary once you return by value
cout << d.toString() << endl;
I was wondering if there was a way i could use it so that in main.cpp
i could use something like:
cout<<base.toString()<<endl;
The above implementation is illegal because base has pure virtual
(abstract).
I'm learning C++, and since I've programmed in Java most of the time,
its getting a little confusing.
Repeat after me. C++ is not Java. When possible, you don't want to
dynamically allocate objects.
Even better is to implement operator<< for base and children:
std::ostream& operator<<(std::ostream& os, const base& b)
{
os << b.toString();
return os;
}
This allows you to avoid the toString(), at least for output constructs.
Thus:
derived d;
std::cout << d << std::endl;