overload operator = with inheritance

This is a discussion on overload operator = with inheritance within the C++ Programming forums, part of the General Programming Boards category; Hello please help me Code: class X { public: virtual void function( ) = 0; protected: int x,y; color cl; ...

  1. #1
    thr
    thr is offline
    Registered User
    Join Date
    Jul 2009
    Posts
    5

    Question overload operator = with inheritance

    Hello please help me
    Code:
    class X
    {
    	public:
    		virtual void function( ) = 0;
    	protected:
    		int x,y;
    		color cl;
    		X-type type;
    		char a;
    };
    class X is abstract class.
    ----------------------------
    class Y : public X
    {
    	private:
    		int counter;
    }
    
    class Z : public X
    {
    	private:
    		int h, s;
    }
    
    -----------------------------
    i want to copy object of derived class to base class
    how can i overload operator = that copy private member of derived class in base class;
    example:
    x* arr[10][10];
    arr[2][2] = new Y( constructor of class Y );
    arr[3][2] = arr [2][2];
    that operator = just copy counter, cl, type, a of arr[2][2] to arr[3][2]
    and how i can initialize to x=3,y=2 of arr[3][2] or x=2, y=2 of arr[2][2]
    example2:
    arr[5][5] = new Z( constructr of class Z );
    arr[a][b] = arr[5][5];
    that a,b variables that user enter
    how i overload operator = for these 3 classes that copy priavate member of derived class 1( Y ) to
    derived class2( Z ) or copy derived class to base class
    ------------------------------------------------------
    i can't find topic operator overloading with inheritance in the books if you
    know books that describe his topic pleas introduce me that book
    thank's

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Your array contains pointers, so = should assign pointers. As far as polymorphism is concerned, I'd imagine the most derived type of both pointers should now be the same.

    It is not quite clear what you mean by copying the members. The base class doesn't have members h and s, so these cannot be copied if you really want to assign a derived class instance to the base class instance. (This is called slicing.)
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #3
    thr
    thr is offline
    Registered User
    Join Date
    Jul 2009
    Posts
    5
    no i dont want copy object of derived class to object of base class but i want to copy pointer of base class that point to object of derived class to pointer od base class that not point to any object for example:
    Code:
    X* arr[10][10];
    arr[0][1] = new Y( costructor of class Y );
    arr[5][6] = arr[0][1];
    or other hand
    i want overload perator = for above example
    left side of operator = is pointer of base class that is not point any object or free
    and right side of operator = is pointer to derived class object.
    i want copy some data member of right side of operator = to left side operator =
    example:
    arr[5][6]=arr[0][1];
    copy color cl, color cl,char a of the arr[0][1] to arr[5][6]
    and x,y of arr[5][6] are---> x=5, y=6
    and then i want to arr[0][1] = 0 or otherhand
    arr[0][1] ---> x=0, y=1
    cl == ???, type = ???, a=???

    how can i do this?
    please help me
    thx

  4. #4
    The larch
    Join Date
    May 2006
    Posts
    3,573
    I think you can't overload pointer assignment. When you assign pointers, both pointers will be pointing to the same object.

    If you want to copy the instance, one might use a virtual clone method:

    Code:
    class X
    {
    public:
        virtual X* clone() const = 0;
        ...
    };
    
    class Y: public X
    {
    public:
        virtual X* clone() const
        {
            return new Y(*this); //for any derived class the implementation could be similar
        }
        ...
    };
    However with that you need to be careful not to leak previously allocated objects.

    Code:
        X* array[2];
        array[0] = new Y(...);
        array[1] = new Y(...);
        array[0] = array[1]->clone(); //allocates new Y, previous pointer held by array[0] is leaked
    I now understand that you want the objects to know their indexes in the array? 1) Do they really need to know that? - Instead of small objects knowing about the context where they are used, you could have another larger class know the context and tell them what they need to know. 2) You might need a class for the array that sets the x and y member after assignment.
    Last edited by anon; 07-17-2009 at 08:21 AM.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  5. #5
    C++11 User Tux0r's Avatar
    Join Date
    Nov 2008
    Location
    Sweden
    Posts
    135
    nice one

  6. #6
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,308
    Quote Originally Posted by thr View Post
    Hello please help me
    Code:
    class X
    {
    	public:
    		virtual void function( ) = 0;
    	protected:
    		int x,y;
    		color cl;
    		X-type type;
    		char a;
    };
    class X is abstract class.
    ----------------------------
    class Y : public X
    {
    	private:
    		int counter;
    }
    
    class Z : public X
    {
    	private:
    		int h, s;
    }
    
    -----------------------------
    i want to copy object of derived class to base class
    how can i overload operator = that copy private member of derived class in base class;
    example:
    x* arr[10][10];
    arr[2][2] = new Y( constructor of class Y );
    arr[3][2] = arr [2][2];
    that operator = just copy counter, cl, type, a of arr[2][2] to arr[3][2]
    and how i can initialize to x=3,y=2 of arr[3][2] or x=2, y=2 of arr[2][2]
    example2:
    arr[5][5] = new Z( constructr of class Z );
    arr[a][b] = arr[5][5];
    that a,b variables that user enter
    how i overload operator = for these 3 classes that copy priavate member of derived class 1( Y ) to
    derived class2( Z ) or copy derived class to base class
    ------------------------------------------------------
    i can't find topic operator overloading with inheritance in the books if you
    know books that describe his topic pleas introduce me that book
    thank's
    How does the top code snippet relate to your arr matrix?
    What is "X-type"?
    Perhaps you should provide a minimal real code example rather than pseudocode with more than you need to demonstrate the issue.

    In many cases a class should not have an assignment operator defined because the auto-generated one will often already do the right thing. If that's not the answer you are looking for then you should:
    1. Modify that example to show a case where it is actually necessary to implement operator=.
    2. Show your attempt at providing the operator= definition for that example.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  7. #7
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,308
    Wait, I think I can answer my first question myself, after taking a second look at that arr bit...
    It appears that you're under the impression that implementing operator= can be implemented for pointers. No, an operator= is implemented for a class or struct. If you're assigning raw pointers around then you're always on your own.

  8. #8
    thr
    thr is offline
    Registered User
    Join Date
    Jul 2009
    Posts
    5
    Code:
       1.
          My example code of my classes
       2.
          class Mohreh
       3.
          {
       4.
           
       5.
          public:
       6.
          Mohreh( int X, int Y, color c, mohreh_type mt, char ch ) : x(X), y(Y), col( c ), type( mt ), a( ch ) { }
       7.
           
       8.
          virtual const Mohreh& operator=( const Mohreh& r )
       9.
          {
      10.
           
      11.
          col = r.col;
      12.
          type = r.type;
      13.
          a = r.a;
      14.
          return *this;
      15.
          }
      16.
          void set( int a, int b )
      17.
          {
      18.
          x=a;
      19.
          y=b;
      20.
          }
      21.
           
      22.
           
      23.
          virtual bool checkmove( int, int ) = 0;
      24.
          virtual void move( int, int ) = 0;
      25.
          color col;
      26.
          char a;
      27.
          protected:
      28.
          int x, y;
      29.
           
      30.
          mohreh_type type;
      31.
           
      32.
           
      33.
          };
      34.
          -------------------
      35.
          extern Mohreh* safheh[8][8];
      36.
           
      37.
          class Asb : public Mohreh
      38.
          {
      39.
          public:
      40.
          Asb( int X, int Y, color c, mohreh_type t, char );
      41.
          const Asb &operator=( const Asb& );
      42.
           
      43.
          bool checkmove( int, int );
      44.
          void move( int, int );
      45.
           
      46.
          };
      47.
          #endif
      48.
          ----------------------
      49.
          #include "Mohreh.h"
      50.
           
      51.
          extern Mohreh* safheh[8][8];
      52.
           
      53.
          class Sarbaz : public Mohreh
      54.
          {
      55.
          public:
      56.
          Sarbaz( int X, int Y, color c, mohreh_type t, char );
      57.
          bool checkmove( int, int );
      58.
          void move( int, int );
      59.
           
      60.
          private:
      61.
          int counter;
      62.
          };
      63.
          #endif
      64.
          -------------------------
      65.
          #include "Mohreh.h"
      66.
           
      67.
          extern Mohreh* safheh[8][8];
      68.
           
      69.
          class Galeh : public Mohreh
      70.
          {
      71.
          public:
      72.
          Galeh( int X, int Y, color c, mohreh_type t, char );
      73.
          bool checkmove( int, int );
      74.
          void move( int, int );
      75.
           
      76.
          };
      77.
          #endif
      78.
          ------------------------
      79.
          function main()
      80.
           
      81.
          #include <iostream>
      82.
          #include "Mohreh.h"
      83.
          #include "Asb.h"
      84.
          #include "Sarbaz.h"
      85.
          #include "Shah.h"
      86.
          #include "Vazir.h"
      87.
          #include "Fil.h"
      88.
          #include "Galeh.h"
      89.
          #include <typeinfo>
      90.
          using namespace std;
      91.
           
      92.
          Mohreh* safheh[8][8];
      93.
           
      94.
          void func( void );
      95.
          void print( void );
      96.
          void zero( void );
      97.
          void deletefunc( void );
      98.
           
      99.
          int main()
     100.
          {
     101.
           
     102.
           
     103.
          safheh[1][0] = new Sarbaz( 1,0, black, sarbaz, '^' );
     104.
          safheh[1][1] = new Sarbaz( 1,1, black, sarbaz, '^' );
     105.
          safheh[1][2] = new Sarbaz( 1,2, black, sarbaz, '^' );
     106.
          safheh[1][3] = new Sarbaz( 1,3, black, sarbaz, '^' );
     107.
          safheh[1][4] = new Sarbaz( 1,4, black, sarbaz, '^' );
     108.
          safheh[1][5] = new Sarbaz( 1,5, black, sarbaz, '^' );
     109.
          safheh[1][6] = new Sarbaz( 1,6, black, sarbaz, '^' );
     110.
          safheh[1][7] = new Sarbaz( 1,7, black, sarbaz, '^' );
     111.
           
     112.
          safheh[6][0] = new Sarbaz( 6,0, white, sarbaz, '^' );
     113.
          safheh[6][1] = new Sarbaz( 6,1, white, sarbaz, '^' );
     114.
          safheh[6][2] = new Sarbaz( 6,2, white, sarbaz, '^' );
     115.
          safheh[6][3] = new Sarbaz( 6,3, white, sarbaz, '^' );
     116.
          safheh[6][4] = new Sarbaz( 6,4, white, sarbaz, '^' );
     117.
          safheh[6][5] = new Sarbaz( 6,5, white, sarbaz, '^' );
     118.
          safheh[6][6] = new Sarbaz( 6,6, white, sarbaz, '^' );
     119.
          safheh[6][7] = new Sarbaz( 6,7, white, sarbaz, '^' );
     120.
           
     121.
          safheh[0][0] = new Galeh( 0,0, black, galeh, '@' );
     122.
          safheh[0][1] = new Asb( 0,1, black, asb, '#' );
     123.
          safheh[0][2] = new Fil( 0,2, black, fil, '%' );
     124.
          safheh[0][3] = new Vazir( 0,3, black, vazir, '$' );
     125.
          safheh[0][4] = new Shah( 0,4, black, shah, '*' );
     126.
          safheh[0][5] = new Fil( 0,5, black, fil, '%' );
     127.
          safheh[0][6] = new Asb( 0,6, black, asb, '#' );
     128.
          safheh[0][7] = new Galeh( 0,7, black, galeh, '@' );
     129.
           
     130.
          safheh[7][0] = new Galeh( 7,0, white, galeh, '@' );
     131.
          safheh[7][1] = new Asb( 7,1, white, asb, '#' );
     132.
          safheh[7][2] = new Fil( 7,2, white, fil, '%' );
     133.
          safheh[7][3] = new Vazir( 7,3, white, vazir, '$' );
     134.
          safheh[7][4] = new Shah( 7,4, white, shah, '*' );
     135.
          safheh[7][5] = new Fil( 7,5, white, fil, '%' );
     136.
          safheh[7][6] = new Asb( 7,6, white, asb, '#' );
     137.
          safheh[7][7] = new Galeh( 7,7, white, galeh, '@' );
     138.
          func( );
     139.
          print( );
     140.
          func( );
     141.
          print( );
     142.
          func( );
     143.
          print( );
     144.
          deletefunc( );
     145.
          return (0);
     146.
          }
     147.
          void func( void )
     148.
          {
     149.
          int x,y,a,b;
     150.
          cout << " Enter X: ";
     151.
          cin >> x;
     152.
          cout << " Enter Y: ";
     153.
          cin >> y;
     154.
          cout << " Enter A: ";
     155.
          cin >> a;
     156.
          cout << " ENTER B: ";
     157.
          cin >> b;
     158.
          safheh[x][y]->move( a,b );
     159.
           
     160.
          }
     161.
           
     162.
          void print( void )
     163.
          {
     164.
           
     165.
          for( int i=0; i < 8; i++ )
     166.
          {
     167.
          for( int l=0; l < 20; l++ )
     168.
          cout << " -";
     169.
          cout << endl;
     170.
          for( int j=0; j < 8; j++ ){
     171.
           
     172.
          cout << " |";
     173.
          if( safheh[i][j] )
     174.
          cout << safheh[i][j]->a;
     175.
          else
     176.
          cout << " ";
     177.
          cout << " |";
     178.
          }
     179.
          cout << endl;
     180.
          }
     181.
           
     182.
          }
     183.
           
     184.
           
     185.
           
     186.
          void deletefunc( void )
     187.
          {
     188.
          for( int i=0; i < 8; i++ )
     189.
          for( int j=0; j < 8; j++ ){
     190.
          if( safheh[i][j] )
     191.
          delete safheh[i][j];
     192.
          }
     193.
          }
     194.
          ---------------------------------------------
     195.
          Asb.cpp
     196.
          #include "Mohreh.h"
     197.
          #include "Asb.h"
     198.
          #include <iostream>
     199.
          using namespace std;
     200.
           
     201.
          Asb::Asb(int X, int Y, color c, mohreh_type t, char ch) : Mohreh( X, Y, c, t, ch ) { }
     202.
           
     203.
          bool Asb::checkmove( int a, int b )
     204.
          {
     205.
          if( ( a < 0 || b > 7 ) || ( b < 0 || b > 7 ) )
     206.
          return false;
     207.
          if( ( a == x ) && ( b == y ) )
     208.
          return false;
     209.
           
     210.
          if( (( a == x-1 && b == y+2 ) || ( a == x-2 && b == y+1)
     211.
          || ( a == x-2 && b == y-1 ) || ( a == x-1 && b == y-2 )
     212.
          || ( a == x+1 && b == y-2 ) || ( a == x+2 && b == y-1 )
     213.
          || ( a == x+2 && b == y+1 ) || ( a == x+1 && b == y+2 ))
     214.
          && ( safheh[ a ][ b ]!= 0 ) && ( safheh[ a ][ b ]->col != col ) )
     215.
          return true;
     216.
          else if( (( a == x-1 && b == y+2 ) || ( a == x-2 && b == y+1)
     217.
          || ( a == x-2 && b == y-1 ) || ( a == x-1 && b == y-2 )
     218.
          || ( a == x+1 && b == y-2 ) || ( a == x+2 && b == y-1 )
     219.
          || ( a == x+2 && b == y +1 ) || ( a == x+1 && b == y+2 ))
     220.
          && (!( safheh[ a ][ b ]!= 0 )) )
     221.
          return true;
     222.
          else
     223.
          return false;
     224.
           
     225.
          }
     226.
           
     227.
          void Asb::move( int a, int b )
     228.
          {
     229.
          if( checkmove( a, b ) == true )
     230.
          {
     231.
           
     232.
          if( safheh[a][b] != 0 )
     233.
          delete safheh[a][b];
     234.
           
     235.
          safheh[a][b] = safheh[x][y]; // I want to copy any data of safheh[x][y] to safheh[a][b] except x, y and set safheh[a][b]---> x, y by under code but operator = dont work
     236.
          //safheh[a][b]->set(a, b );
     237.
           
     238.
          safheh[x][y] = 0;
     239.
          //safheh[a][b]->x = a;
     240.
          //safheh[a][b] -> y = b;
     241.
           
     242.
           
     243.
          }
     244.
          else
     245.
          cout << "Shoma nemitavanid in harekat ra anjam dahid\n";
     246.
          }
     247.
           
     248.
          const Asb &Asb::operator =( const Asb &r )
     249.
          {
     250.
          Mohreh::operator =( r );
     251.
          return *this;
     252.
          }
     253.
          -------------------------------------
     254.
          enter x=7
     255.
          enter y=6
     256.
          enter a=5
     257.
          enter b= 5
     258.
          dont copy safheh[7][6] to safheh[5][5]
    i want to overload operator = for base class and derived classes plz help me

  9. #9
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Great, a large file without indentation and embedded line numbers, so one couldn't possible try to compile it.

    As I understand this is a chess game, and you are expecting that after you do something like:
    Code:
    board[1][1] = new Pawn(1, 1,...);
    board[3][1] = board[1][1];
    the Pawn now knows that it has been moved to (3, 1).

    This is not going to happen:
    1) You can't overload operator= for pointers.
    2) Even if you could, all this has little to do with operator=. An assignment operator doesn't know nor care whether the assignment happens between simple instances, array elements, vector/list/map contents or what-not.

    You need something like a move method (both for a board class and a chess piece class):
    Code:
    void ChessPiece::move(int x, int y)
    {
        this->x = x;
        this->y = y;
    }
    
    void ChessBoard::move(int from_x, int from_y, int to_x, int to_y)
    {
        if (data[from_x][from_y] && data[from_x][from_y]->can_move(to_x, to_y)) { //see if there's a piece
            if (data[to_x][to_y]) { //see if there already is a piece at the target
                delete data[to_x][to_y];
            }
            data[to_x][to_y] = data[from_x][from_y];
            data[from_x][from_y] = 0;
            data[to_x][to_y]->move(to_x, to_y);
        }
    }
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  10. #10
    thr
    thr is offline
    Registered User
    Join Date
    Jul 2009
    Posts
    5
    hello anon
    thank you
    i can solve my problem with your guidance
    very thx

  11. #11
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,308
    Several problems here:
    Code:
          virtual const Mohreh& operator=( const Mohreh& r )
          {
          col = r.col;
          type = r.type;
          a = r.a;
          return *this;
          }
    First of all, it really does not make sense for an assignment operator to be virtual.
    Second, the automatically generated assignment operator calls operator = for each member in the class/struct. This is exactly the same as what you're doing here! That means you should delete this function entirely. Otherwise if you later added another member and forgot to update this function you'd get a bug that could have been avoided. Not to mention it's then shorter and will hide less other bugs and the auto-generated on might even be faster. A derived class can still call Mohreh::operator= when it is automatically generated.
    Your classes should all always obey "The rule of three". In this instance following it only means re-enforcing that you did not need to implement operator=, rather than needing to also implement the copy-constructor and destructor.

    This is almost the correct way to implement operator= for a derived class:
    Code:
          const Asb &Asb::operator =( const Asb &r )
          {
          Mohreh::operator =( r );
          return *this;
          }
    But again, this piece of code isn't actually necessary at all, and the program would be much better without it.

    Also, returning a const reference from operator= isn't the normal thing to do. It prevents you from doing things like this, which might irk some people:
    Code:
    (to = from).nonConstFunction();
    If you really need some practice implementing operator= etc (which is probably true) then I highly suggest you pick a case where it is actually necessary.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 06-08-2009, 04:03 PM
  2. Multiple Inheritance - Size of Classes?
    By Zeusbwr in forum C++ Programming
    Replies: 10
    Last Post: 11-26-2004, 09:04 AM
  3. inheritance and performance
    By kuhnmi in forum C++ Programming
    Replies: 5
    Last Post: 08-04-2004, 01:46 PM
  4. Having trouble with operator*=()
    By Lurker in forum C++ Programming
    Replies: 10
    Last Post: 10-26-2003, 03:03 PM
  5. Inheritance vs Composition
    By Panopticon in forum C++ Programming
    Replies: 11
    Last Post: 01-20-2003, 04:41 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21