I do not understand why an error and how to solve it. (An error on invoking attributes in the constructor) one

class shader { public: shader() { attributes(); } virtual void attributes() = 0; }; class staticShader : public shader { public: staticShader() : shader() { }; void attributes() override { std::cout << "attribute"; } }; int main() { staticShader shader{}; system("pause"); return 0; } 

class shader { public: shader() { attributes(); } virtual void attributes() = 0; }; class staticShader : public shader { public: staticShader() : shader() { }; void attributes() override { std::cout << "attribute"; } }; int main() { staticShader shader{}; system("pause"); return 0; }

    1 answer 1

    Because when you call the virtual function of attributes () from the constructor of the shader class, an object of class staticShader is not created yet, respectively, there is no method to call.

    Replace:

     virtual void attributes() = 0; 

    on

     virtual void attributes() { std::cout << "base::attribute"; } 

    And you will see that even though you create a staticShader class object, its virtual function will not be called.

    • I do not understand the point if I create an absolute virtual function that cannot be called in the constructor then why is it needed. mmm yes ... - ARTEM Frolov
    • No one bothers to call a function in the constructor of the class in which it is defined. In this case, it is staticShader. - Zefick
    • @ ARTEM Frolov, what is the problem to create an object and then immediately call a virtual function, what is the need to call it from the constructor? - Alexander
    • @Alexander I understood 1 that with ++ designers it is better to replace with initialization methods. Thanks for the explanation. - ARTEM Frolov
    • @ ARTEMFrolov, then replace immediately and destructors. Virtual functions cannot be called in them either - yrHeTaTeJlb