If operator=() is private in base.....

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • qazmlp

    If operator=() is private in base.....

    If base declares operator=() as private, is it possible for the
    derived class to declare operator=() as public and allow assignment
    access for it?
    If no, why is it restricted so?
  • Peter Koch Larsen

    #2
    Re: If operator=() is private in base.....


    "qazmlp" <qazmlp1209@red iffmail.com> skrev i en meddelelse
    news:db9bbf31.0 402150324.651eb 543@posting.goo gle.com...[color=blue]
    > If base declares operator=() as private, is it possible for the
    > derived class to declare operator=() as public and allow assignment
    > access for it?[/color]
    Yes[color=blue]
    > If no, why is it restricted so?[/color]
    It is not, but you might have problems declaring a sensible operator=
    considering the base class does not define this operation.

    /Peter


    Comment

    • Rolf Magnus

      #3
      Re: If operator=() is private in base.....

      qazmlp wrote:
      [color=blue]
      > If base declares operator=() as private, is it possible for the
      > derived class to declare operator=() as public and allow assignment
      > access for it?[/color]

      Yes. You can do that with any member function or operator.

      Comment

      • Sharad Kala

        #4
        Re: If operator=() is private in base.....


        "qazmlp" <qazmlp1209@red iffmail.com> wrote in message
        news:db9bbf31.0 402150324.651eb 543@posting.goo gle.com...[color=blue]
        > If base declares operator=() as private, is it possible for the
        > derived class to declare operator=() as public and allow assignment
        > access for it?
        > If no, why is it restricted so?[/color]

        Think it this way. Each derived object has a base part.
        You want to keep assignment operator in base to be private.
        That means you can't invoke bases' assignment operator from the derived class.
        Which in turn means that when you assign objects you will keep
        base part of the old object and derived part of the object you are assigning
        from.

        Consider this example code -

        #include <iostream>
        class A{
        public:
        int i;
        A(int i): i(i){}
        private:
        A& operator=(const A& a)
        {
        this->i = a.i;
        return *this;
        }
        };

        class B: public A{
        public:
        int j;
        B(int i, int j): A(i), j(j) {}
        B& operator=(const B&b)
        {
        // Can't invoke base assignment operator.
        // A::operator=(b) ;
        this->j= b.j;
        return *this;
        }
        };

        int main(){
        B b1(5, 2), b2(6, 4);
        b1=b2;
        std::cout << b1.i << " " << b1.j;
        }

        Output - 5 4
        See the difference?

        -Sharad


        Comment

        Working...