Search code examples
c++assignment-operator

Big 3 - Assignment operator


I'm working on developing a blackjack game. In my blackjack game I created a class called Dealer. I added in the "Big 3" into the class since I'm using resource on the heap. In my int main(), I created two pointers of type Dealer and set it to each other; however, for some reason when I run the debugger it doesn't go to the assign operator that I created in the Dealer class. Can anyone educate me as to why it doesn't go to the assign operator created in the Dealer Class? Why does the assign operator only work for non-pointer variable of type Dealer?

class Dealer
{
public:
    Dealer();
    Dealer(Deck*);
    Dealer& operator=(const Dealer&); // assign operator
    Dealer(const Dealer&); //copy constructor
    ~Dealer();//deconstructor
private:
    vector<Card*> myCards;
    Deck *deckOfCards;
};

Dealer::Dealer()
{
    deckOfCards = new Deck();

}
Dealer::Dealer(Deck *t)
{
    deckOfCards = t;

}
//copy constructor
Dealer::Dealer(const Dealer& rightSide)
{
    deckOfCards = new Deck();
    for (size_t x= 0; rightSide.myCards.size(); x++)
    {
        myCards[x] = rightSide.myCards[x];//copying of the vector
    }

}
//Assignment Operator
Dealer& Dealer::operator=(const Dealer& rhs)
{
    if(this != &rhs)
    {
        delete deckOfCards;
        for(size_t x = 0; x < myCards.size(); x++)
        {
            delete [] myCards[x];
        }
        myCards.clear();

        deckOfCards = rhs.deckOfCards; //copy for Deck *deckOfCards

        for (size_t x= 0; rhs.myCards.size(); x++)
        {
            myCards[x] = rhs.myCards[x];//copying of the vector
        }    
    }
    return *this;

 }
//Destructor
Dealer::~Dealer()
{
     delete deckOfCards;
    for(size_t x = 0; x < myCards.size(); x++)
    {
        delete [] myCards[x];
    }
    myCards.clear();     
}

int main()
{
    Deck* p = new Deck();
    Deck *b = new Deck();
    p->shuffle();
    p->Display();    
    b = p; //does not apply the assign operator
    b->Display();
    b->shuffle();
    b->Display();
//    Deck f;
//    Deck g;  
//    f.shuffle();
//    g = f;  // This goes to the assignment operator function 
//    f.Display();
//    g.shuffle();
//    g.Display();
}

Solution

  • Because assignment methods are used for copying (in the loose sense of the word, technically it should probably be 'assigning') an object, not for copying normal pointers to objects.

    By definition, when you copy a pointer, you want it pointing at the exact same thing, otherwise it's not actually a copy. So, all you get is a copy of the address of your object, there's zero need to invoke any member functions for that.