inheritance - operator= and functions that are not inherited in C++? -


until test i've made, believed constructors not inherited in c++. apparently, assignment operator= not too...

  1. what reason of ?
  2. is there workaround inherit assignment operator ?
  3. is case operator+=, operator-=, ... ?
  4. are other functions (apart constructors/operator=) inherited ?

in fact, encountered problem doing crtp :

template<class crtp> class base {     inline crtp& operator=(const base<crtp>& rhs) {/*something*/; return static_cast<crtp&>(*this);} };  class derived1 : public base<derived1> { };  class derived2 : public base<derived2> { }; 

is there solution working ?

edit : ok, have isolated problem. why following isn't working ? how solve problem ?

#include <iostream> #include <type_traits>  // base class template<template<typename, unsigned int> class crtp, typename t, unsigned int n> class base {     // cast base     public:         inline base<crtp, t, n>& operator()()         {             return *this;         }      // operator =     public:         template<typename t0, class = typename std::enable_if<std::is_convertible<t0, t>::value>::type>         inline crtp<t, n>& operator=(const t0& rhs)         {             (unsigned int = 0; < n; ++i) {                 _data[i] = rhs;             }             return static_cast<crtp<t, n>&>(*this);         }      // data members     protected:         t _data[n]; };  // derived class template<typename t, unsigned int n> class derived : public base<derived, t, n> { };  // main int main() {     derived<double, 3> x;     x() = 3; // <- ok     x = 3;   // <- error: no match 'operator=' in ' x=3 '     return 0; } 

the assignment operator technically inherited; however, hidden explicitly or implicitly defined assignment operator derived class (see comments below).

(13.5.3 assignment) assignment operator shall implemented non-static member function 1 parameter. because copy assignment operator operator= implicitly declared a class if not declared user, base class assignment operator hidden copy assignment operator of derived class.

you can implement dummy assignment operator forwards call base class operator=, this:

// derived class template<typename t, unsigned int n> class derived : public base<derived, t, n> { public:     template<typename t0, class = typename std::enable_if<std::is_convertible<t0, t>::value>::type>     inline derived& operator=(const t0& rhs)     {         return base<derived, t, n>::operator=(rhs);     } }; 

Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -