But then again... since you have an inheritance chain you don't have to overload, just redefine Get in class B and when you call it from a B object it will override the old Get (defined in class A).
However, a new problem arises... what if you wanted to call Get for a derived object pointed to by a base pointer? You want B Get to be called but you are calling it by an A pointer...
The answer is simple, just make Get a virtual function and you're ok... (try to remove the virtual keyword to see that the last Get call returns A instead of the desired B ;) )
#include <iostream>
usingnamespace std;
class A
{
public:
virtual A * Get()
{
cout << "returning A..." << endl;
returnthis;
}
};
class B : public A
{
public:
//don't have to put the virtual keyword here
//but it's a good habit (IMHO)
virtual B * Get() {
cout << "returning B..." << endl;
returnthis;
}
};
int main()
{
A a, *pa;
B b, *pb;
pa=a.Get();
pb=b.Get();
pa=&b;
pb=(B*)pa->Get();
cout << "hit enter to quit..." << endl;
cin.get();
return 0;
}
Why not just downcast normally? dynamic_cast exists for this very reason:
1 2 3 4 5 6 7 8 9 10 11 12
A* a = /*whatever */;
B* b;
b = dynamic_cast<B*>(a);
if(b)
{
// successful downcast, 'a' really did point to a 'B'
}
else
{
// invalid downcast. 'a' did not point to a 'B'
}
Of course one would have to question why you'd need to downcast. Downcasting can often be avoided with a better design.
It probably is poor design on my part, I don't know how to do it better though. If anyone wants to spruce it up a bit, that would be awesome.
Purpose:
Wrapper class around ofstream that writes to file. After every line write, the file is closed, so whatever is in the stream is always committed to file rather than being lost due to unexpected escape/crash. Does a few other things as well.
This system is used by several projects(within the same solution), so I created a base type in a different file that any of the other projects can access and then derived a type tailored to each project.
The issue is outlined below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//Before
class cFileObjBase
{
public:
cFileObjBase& operator<<(constchar *ch);
};
//---
class cFileObj : public cFileObjBase
{
public:
cFileObj &operator<<( const Packet *pack );
};