uchar
uchar

Reputation: 2590

inheriting from child and calling child's function not working in visual studio 2013

In the following code :

#include <iostream>
using namespace std;

template<class T >
class Setting
{
public:
    Setting(Setting* instance){
        ((T*)instance)->write();
    };
    Setting(){ write(); };
    virtual void write(){ cout << "in parent\n"; }
};

class child :public Setting<child>
{
public:
    child() :Setting(this){};
    virtual void write(){ cout << "in child\n"; }
};
int main()
{
    child ch;
}

g++ prints "in child" which is exactly what I want .( http://coliru.stacked-crooked.com/a/4304ab99ebd894b3)

But in visual studio 2013 output is "in parent" !!!(http://rextester.com/EMQ5448)

why?? Is there any alternative way for getting the same result in visual studio?

Upvotes: 1

Views: 127

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

"why?? Is there any alternative way for getting the same result in visual studio?"

Because compiler implementations seem to differ when handling this syntax.
It seems like if write() is declared as a virtual function, VS2013 always tries to resolve it from the vtable, instead of using the method from the (not yet) instantiated derived class (disrespecting the static_cast<>).

I've got your sample working when removing the virtual keywords from your write() function declarations, like this

template<class T >
class Setting {
public:
    Setting(){ static_cast<T*>(this)->write(); };

    void write(){ cout << "in parent\n"; } // Note: No virtual
};

class child :public Setting<child> {
public:
    child() {};
    void write(){ cout << "in child\n"; }  // Note: No virtual
};

int main() {
    child ch;
}

Though this works, you seriously should obey, not to rely on any state established from the child class constructor, when calling write from the base class.


You also want to read about some additional references what the CRTP pattern, and using static polymorphism (that's all about avoiding the virtual) actually is about.

Upvotes: 1

Related Questions