[C++] Inheritance not working from constructor?

Started by
10 comments, last by fyhuang 18 years, 9 months ago
I think you can do it this way, though it will requier the use of templates:
template <typename T>class A{ public:    void printHello() { std::cout << "A::printHello()" << std::endl; }    A()    {       static_cast<T*>(this)->printHello();    }};class B: public A<B>{  public:     void printHello() { std::cout << "B::printHello()" << std::endl; }};B b; // outputs "B::printHello()"

The problem with this is that the printHello() method must be public, which is not always what you want.
Advertisement
Hey all,

I eventually implemented JohnBolton's suggestion, and it appears to work well enough. Mattnewport, I think I'm going to implement yours too, cause now that I think of it I don't see any reason for keeping the destruction code in shutdown(). I still think it's important to keep init code in init() so that, if something goes wrong, at least the object is fully constructed and I can now safely return an error, throw an exception, whatever. That's just me though.

Thanks and cheers!
- fyhuang [ site ]

This topic is closed to new replies.

Advertisement